Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ITextSharp edit an existing pdf

Tags:

c#

itextsharp

I want to add a text to an existing PDF file using iTextSharp, I found different ways but in all of them the writer and reader are separate pdf files. I want a way so I can open a pdf then write different things in different positions. right now I have this code, but it makes a new file.

using (FileStream stream1 = File.Open(path, FileMode.OpenOrCreate))
      {
      BaseFont bf = BaseFont.CreateFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
      PdfReader reader = new PdfReader("C:\\26178DATA\\pdf\\holding.pdf");
      var pageSize = reader.GetPageSize(1);
      PdfStamper stamper = new PdfStamper(reader, stream1);
      iTextSharp.text.Font tmpFont = new iTextSharp.text.Font(bf, fontSize);
      PdfContentByte canvas = stamper.GetOverContent(1);
      Phrase ph = new Phrase(words[1], tmpFont);
      ph.Font = tmpFont;
      canvas.SetFontAndSize(bf, fontSize);
      ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT, ph, iTextSharp.text.Utilities.MillimetersToPoints(x * 10), pageSize.GetTop(iTextSharp.text.Utilities.MillimetersToPoints(y * 10)), 0);
      stamper.Close();
            }
like image 245
Mina N Avatar asked Feb 01 '13 04:02

Mina N


1 Answers

You want to add a text to an existing PDF file using iTextSharp, found different ways but in all of them the writer and reader are separate pdf files.

As the normal way in which iText(Sharp) manipulates a PDF using a PdfStamper, can involve major reorganization of existing PDF elements, iText does not edit a file in place. The other way, using append mode, would allow for editing in place; but such an option is not implemented. A big draw-back of in-place editing is that in case of some program failure, the file in question might remain in an intermediary, unusable state.

That being said, you can save the new file to the path of the original file by first reading the file into memory completely and then starting to create the output with the same path. In case of your sample code that would imply at least moving the PdfReader constructor use before the creation of the output stream:

PdfReader reader = new PdfReader(path);
using (FileStream stream1 = File.Open(path, FileMode.OpenOrCreate))
{
    BaseFont bf = BaseFont.CreateFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    ...

Alternatively you could create the result file in memory, i.e. in a MemoryStream instead of a FileStream, and, when finished, write the contents of the memory stream to your source file path.

like image 147
mkl Avatar answered Sep 28 '22 04:09

mkl