Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an image to an existing PDF file with iText7

Tags:

c#

pdf

itext7

I want to add an image to a specific position inside an existing PDF file using iText7.
In a different project using iTextSharp, the code was very simple:

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);

But I do not find the correct way to do it with iText7.
I have a PdfReader and a PdfWriter but where can I find the PdfStamper in iText7?
Or maybe there is a different way to add an image to an existing PDF file in iText7?
(I can't use iTextSharp in current project)

like image 910
Mina Shtraicher Avatar asked Jan 14 '18 15:01

Mina Shtraicher


People also ask

What is PdfStamper?

PdfStamper(PdfReader reader, OutputStream os) Starts the process of adding extra content to an existing PDF document. PdfStamper(PdfReader reader, OutputStream os, char pdfVersion) Starts the process of adding extra content to an existing PDF document.


1 Answers

In iText7, there is no PdfStamper anymore. PdfDocument is responsible for modifying the contents of the document.

To add an image to a page, the easiest way is to use Document class from layout module. With that you almost don't have to care about anything.

To add an image to a specific page at a specific position, you need the following code:

// 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();
like image 87
Alexey Subach Avatar answered Oct 22 '22 11:10

Alexey Subach