2013-03-06 21 views
2

我迷失在眼下。 我试图完成的是在另一个上添加一个PDF(如水印)。 问题是,我似乎不明白所使用的坐标系,因为我的水印 只是表现出意外。导入PDF位置PDFStamper

这两个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的位置,然后它在页面上垂直居中。

有人可以给我一个小费吗?

+0

我现在发现的是interessting。如果我用Sourcepdf的PageSize创建一个新文档,结果会有不同的页面大小。看起来像是页面大小和“可见大小”之类的东西。那有意义吗 ? – traffiq 2013-03-06 09:54:29

+0

所以我解决了这个问题。 问题是,sourcepdf有一个裁剪框 - 所以我只需要纠正我的x和y位置的信息:Rectangle cropBox = pdfSource.GetCropBox(iPage); float xCorrected = 0 + cropBox.Left; float yCorrected = 0 + cropBox.Bottom; background.AddTemplate(importatedPage,xCorrected,yCorrected); } } – traffiq 2013-03-06 10:07:54

+1

很好,你解决了你的问题。顺便说一句,这表明为什么这些问题有必要提供PDF本身以供检查。 (作为旁边的评论:'背景= stamper.GetOverContent'似乎很奇怪,因为** OverContent **是*前景*而** UnderContent **是*背景。*) – mkl 2013-03-06 10:49:10

回答

3

所以我解决了这个问题。 的问题是,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。