【问题标题】:iTextSharp: How to add image of PDF as movable element?iTextSharp:如何将 PDF 的图像添加为可移动元素?
【发布时间】:2016-04-14 19:23:12
【问题描述】:

使用 iTextSharp 向 PDF 添加内容,我可以使用以下代码添加另一个 PDF 的图像:

    void addImageFromPDF(string inputPath, string imagePath, string outputPath, int pageNumber)
    {
        PdfReader pdfReader_image = new PdfReader(imagePath);
        PdfReader pdfReader = new PdfReader(inputPath);
        PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(outputPath, FileMode.Create));
        PdfImportedPage page = pdfStamper.GetImportedPage(pdfReader_image, 1);
        pdfStamper.GetOverContent(pageNumber).AddTemplate(page, 100, 100);
        pdfStamper.Close();
    }

但是,这会将图像 PDF 添加为静态元素——我无法单击一次以突出显示它,然后拖动它或删除它,就像我可以使用注释一样。有没有办法创建一个以PdfImportedPage 为内容的PdfAnnotation(或可移动的图形元素)?

【问题讨论】:

  • 您确定 PDF 规范中允许这样做吗?
  • @RadLexus,是的。如果您创建一个源为 PDF 图像的自定义图章,您可以将该图像印在另一个 PDF 上,然后拖动它。
  • @RadLexus 请查看此 PDF 并移动 iText 徽标:gitlab.itextsupport.com/itext/sandbox/raw/master/cmpfiles/…

标签: c# pdf itextsharp


【解决方案1】:

请查看stamp_annotation.pdf 文档。本文档带有带有 iText 徽标的图章注释。由于它是一个注释,因此在 Adob​​e Reader 中查看文档的用户可以移动它(这在其他 PDF 查看器中可能无法正常工作)。

这个例子的代码可以在这里找到:AddStamp

public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
    PdfReader reader = new PdfReader(src);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
    Image img = Image.getInstance(IMG);
    float w = img.getScaledWidth();
    float h = img.getScaledHeight();
    Rectangle location = new Rectangle(36, 770 - h, 36 + w, 770);
    PdfAnnotation stamp = PdfAnnotation.createStamp(
            stamper.getWriter(), location, null, "ITEXT");                     
    img.setAbsolutePosition(0, 0);
    PdfContentByte cb = stamper.getOverContent(1);
    PdfAppearance app = cb.createAppearance(w, h);
    app.addImage(img);
    stamp.setAppearance(PdfName.N, app);
    stamp.setFlags(PdfAnnotation.FLAGS_PRINT);
    stamper.addAnnotation(stamp, 1);
    stamper.close();
    reader.close();
}

在此示例中,我们将戳记注释添加到现有文档中。如果您从头开始创建文档,则需要将stamper.getWriter() 替换为writer,将stamper.getOverContent(1) 替换为writer.getDirectContent(),将stamper.addAnnotation(stamp, 1) 替换为writer.addAnnotation(stamp)

【讨论】:

  • 是否可以在android中实现相同的功能。这段代码会有帮助吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 2016-02-12
  • 1970-01-01
  • 2013-07-10
  • 1970-01-01
  • 2015-11-09
  • 1970-01-01
相关资源
最近更新 更多