原因
OP的覆盖.pdf https://dl.dropboxusercontent.com/u/21842502/picas/overlay.pdf页面内容开头为
/Cs1 cs
1 sc
0.1400146 841.945 m
595.14 841.945 l
595.14 -0.05499268 l
0.1400146 -0.05499268 l
h
f
0.1400146 841.945 m
595.14 841.945 l
595.14 -0.05499268 l
0.1400146 -0.05499268 l
h
f
这些操作绘制两个白色(CS1是一个灰度颜色空间)矩形几乎覆盖了整个MediaBox [0, 0, 595.28, 841.89]
除了顶部和左侧的一条非常细的线之外
因此,将此页面内容放置在另一个页面上,完全覆盖了该其他页面的所有现有内容,这正是您所观察到的:
“document.pdf”的原始内容被覆盖内容完全覆盖
通常只有覆盖一个不能覆盖所有内容的页面才有意义。
使用混合模式的解决方法Darken
或者,您可能想尝试使用混合模式进行叠加Darken which 选择背景颜色和源颜色中较暗的一个, 背景被替换为光源,其中光源较暗;否则,它保持不变。
在Java中(我没有使用Scala的经验,所以我希望你可以利用Java源代码)你可以使用如下方法:
void overlayWithDarkenBlendMode(PDDocument document, PDDocument overlay) throws IOException
{
PDXObjectForm xobject = importAsXObject(document, (PDPage) overlay.getDocumentCatalog().getAllPages().get(0));
PDExtendedGraphicsState darken = new PDExtendedGraphicsState();
darken.getCOSDictionary().setName("BM", "Darken");
List<PDPage> pages = document.getDocumentCatalog().getAllPages();
for (PDPage page: pages)
{
Map<String, PDExtendedGraphicsState> states = page.getResources().getGraphicsStates();
if (states == null)
states = new HashMap<String, PDExtendedGraphicsState>();
String darkenKey = MapUtil.getNextUniqueKey(states, "Dkn");
states.put(darkenKey, darken);
page.getResources().setGraphicsStates(states);
PDPageContentStream stream = new PDPageContentStream(document, page, true, false, true);
stream.appendRawCommands(String.format("/%s gs ", darkenKey));
stream.drawXObject(xobject, 0, 0, 1, 1);
stream.close();
}
}
PDXObjectForm importAsXObject(PDDocument target, PDPage page) throws IOException
{
final PDStream xobjectStream = new PDStream(target, page.getContents().createInputStream(), false);
final PDXObjectForm xobject = new PDXObjectForm(xobjectStream);
xobject.setResources(page.findResources());
xobject.setBBox(page.findCropBox());
COSDictionary group = new COSDictionary();
group.setName("S", "Transparency");
group.setBoolean(COSName.getPDFName("K"), true);
xobject.getCOSStream().setItem(COSName.getPDFName("Group"), group);
return xobject;
}
(OverlayWithEffect.java https://github.com/mkl-public/testarea-pdfbox1/blob/master/src/test/java/mkl/testarea/pdfbox1/assembly/OverlayWithEffect.java)
将它们应用到您的示例文档中
@Test
public void testOverlayWithDarkenVolker() throws COSVisitorException, IOException
{
try ( InputStream sourceStream = getClass().getResourceAsStream("document1.pdf");
InputStream overlayStream = getClass().getResourceAsStream("overlay.pdf") )
{
final PDDocument document = PDDocument.load(sourceStream);
final PDDocument overlay = PDDocument.load(overlayStream);
overlayWithDarkenBlendMode(document, overlay);
document.save(new File(RESULT_FOLDER, "document1-with-overlay.pdf"));
}
}
结果是
如您所见,这两个数字都来自文件1.pdf https://dl.dropboxusercontent.com/u/21842502/picas/document1.pdf以及来自的行覆盖.pdf https://dl.dropboxusercontent.com/u/21842502/picas/overlay.pdf在那儿。
Beware!此代码是概念验证,尚未准备好用于一般生产用途。它例如完全忽略Rotate页面条目...