【问题标题】:Add an image to an existing PDF file with iText7使用 iText7 将图像添加到现有 PDF 文件
【发布时间】:2018-06-23 09:16:15
【问题描述】:

我想使用 iText7 将图像添加到现有 PDF 文件中的特定位置。
在另一个使用 iTextSharp 的项目中,代码非常简单:

iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(new Uri(fullPathSignature));
// Set img size and location on page
//-------------------------------------
// item.Width, item.Height
img.ScaleAbsolute(120, 62);

// left: item.X bottom: item.Y
img.SetAbsolutePosition(25, 25);
//-------------------------------------

//Add it to page 1 of the document,
PdfContentByte cb = stamper.GetOverContent(1);
cb.AddImage(img);

但我没有找到使用 iText7 的正确方法。
我有一个 PdfReader 和一个 PdfWriter,但我在哪里可以找到 iText7 中的 PdfStamper?
或者也许有不同的方法可以将图像添加到 iText7 中的现有 PDF 文件?
(我不能在当前项目中使用 iTextSharp)

【问题讨论】:

    标签: c# pdf itext7


    【解决方案1】:

    在 iText7 中,不再有 PdfStamperPdfDocument负责修改文档内容。

    要将图像添加到页面,最简单的方法是使用来自layout 模块的Document 类。有了它,您几乎不必关心任何事情。

    要将图像添加到特定页面的特定位置,您需要以下代码:

    // Modify PDF located at "source" and save to "target"
    PdfDocument pdfDocument = new PdfDocument(new PdfReader(source), new PdfWriter(target));
    // Document to add layout elements: paragraphs, images etc
    Document document = new Document(pdfDocument);
    
    // Load image from disk
    ImageData imageData = ImageDataFactory.Create(imageSource);
    // Create layout image object and provide parameters. Page number = 1
    Image image = new Image(imageData).ScaleAbsolute(100, 200).SetFixedPosition(1, 25, 25);
    // This adds the image to the page
    document.Add(image);
    
    // Don't forget to close the document.
    // When you use Document, you should close it rather than PdfDocument instance
    document.Close();
    

    【讨论】:

    • 感谢 Alexey,我尝试了您的建议,但得到 NullReferenceException: object reference not set to an instance of an object。
    • @MinaShtraicher 这很奇怪,因为解决方案非常简单并且对我有用。 NullReferenceException 确实没有位置。你确定你通过了正确的imageSource。哪个操作导致异常?
    • 当我到达“document.Add(image);”我得到对象引用未设置为对象的实例。我的代码: iText.Kernel.Pdf.PdfDocument pdf = new iText.Kernel.Pdf.PdfDocument(reader, writer); iText.Layout.Document 文档 = 新 iText.Layout.Document(pdf);浮动 x = 25;浮动 y = 25;浮动 w = 120;浮动 h = 62; ImageData imageData = ImageDataFactory.Create(new Uri(fullPathSignature)); iText.Layout.Element.Image image = new iText.Layout.Element.Image(imageData).ScaleAbsolute(w, h).SetFixedPosition(1, x, y); document.Add(image);
    • 图像源有效。它适用于我在另一个项目中用 iTextSharp 编写的代码。
    • 您可以分享您要修改的 PDF 吗?
    猜你喜欢
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 2020-10-10
    • 2017-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多