我现在迷路了。 我试图完成的是将一个 PDF 添加到另一个 PDF 上(如水印)。 问题是我似乎不理解所使用的坐标系,因为 我的水印表现出乎意料。
两个 PDF 的尺寸不同。
我的目标有以下维度:
595高度
842宽度
要添加的 PDF 具有以下尺寸:
41高度
552宽度
在我的代码中,我执行以下操作:
public bool AddPdf(ref PdfReader pdfSource, ref PdfReader pdfTarget, ref FileStream destination)
{
PdfStamper stamper = null;
try
{
stamper = new PdfStamper( pdfSource, destination );
PdfImportedPage importatedPage = stamper.GetImportedPage(pdfTarget, 1);
PdfContentByte background;
for (int iPage = 1; iPage <= pdfSource.NumberOfPages; iPage++)
{
background = stamper.GetOverContent(iPage);
background.AddTemplate(importatedPage, 0, 0 + importHeight);
}
}
当我这样做时,我希望我的水印出现在左下角。 相反,它位于页面的某个位置(我没有看到它)。只是为了测试,我将 600 硬编码为 y 位置,然后它在页面上垂直居中。
有人可以给我提示吗?
最佳答案
所以我解决了这个问题。 问题是 sourcepdf 有一个裁剪框 - 我只需要使用该信息纠正我的 x 和 y 位置:
PdfStamper stamper = null;
try
{
stamper = new PdfStamper(pdfSource, destination);
PdfImportedPage importatedPage = stamper.GetImportedPage(pdfTarget, 1);
PdfContentByte background;
for (int iPage = 1; iPage <= pdfSource.NumberOfPages; iPage++)
{
background = stamper.GetOverContent(iPage);
// here comes the important part
Rectangle cropBox = pdfSource.GetCropBox(iPage);
float xCorrected = 0 + cropBox.Left;
float yCorrected = 0 + cropBox.Bottom;
background.AddTemplate(importatedPage, xCorrected, yCorrected);
}
}
请记住,如果您要在原件上标记的 pdf 也有裁剪框,则需要再次将该裁剪框的 x,y 减少 x,y。
关于itext - 导入 PDF 位置 PDFStamper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15243548/