Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDFsharp edit a pdf file

Tags:

Environment - PDFsharp Library, Visual Studio 2012 and C# as the language.

I am trying to:

  1. read Test1.pdf (Width = 17 inches, Height – 11 inches) with 1 page
  2. add some text to it
  3. save it as another file (Test2.pdf)

I am able to do all the following. But when I open the file Test2.pdf the size of the page is getting reduced to Width = 11 inches, Height – 11 inches. These PDF files that I am using are Product Specification Sheets that I have downloaded from the internet. I believe this is happening on only certain types of file and I am not sure how to differentiate these files.

Code given below:

//File dimentions - Width = 17 inches, Height - 11 inches (Tabloid Format) PdfDocument pdfDocument = PdfReader.Open(@"D:\Test1.pdf", PdfDocumentOpenMode.Modify);  PdfPage page = pdfDocument.Pages[0]; XGraphics gfx = XGraphics.FromPdfPage(page); XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic); gfx.DrawString("Hello, World!", font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);  //When the file is saved dimentions change to - Width = 11 inches, Height - 11 inches pdfDocument.Save(@"D:\Test2.pdf"); 

I have uploaded the file here Test1.pdf

==================================================================================

As suggested by the PDFsharp Team the code should be as follows:

PdfDocument PDFDoc = PdfReader.Open(@"D:\Test1.pdf", PdfDocumentOpenMode.Import); PdfDocument PDFNewDoc = new PdfDocument();  for (int Pg = 0; Pg < PDFDoc.Pages.Count; Pg++) {     PdfPage pp = PDFNewDoc.AddPage(PDFDoc.Pages[Pg]);      XGraphics gfx = XGraphics.FromPdfPage(pp);     XFont font = new XFont("Arial", 10, XFontStyle.Regular);     gfx.DrawString("Hello, World!", font, XBrushes.Black, new XRect(0, 0, pp.Width, pp.Height), XStringFormats.BottomCenter); }  PDFNewDoc.Save(@"D:\Test2.pdf"); 
like image 869
Yuvi Dagar Avatar asked Jul 15 '13 06:07

Yuvi Dagar


People also ask

Is PDFsharp free?

PDFsharp and MigraDoc Foundation are published Open Source and under the MIT License and are free to use.


1 Answers

Instead of modifying the document, please create a new document and copy the pages from the old document to the new document.

Sample code can be found in this post on the PDFsharp forum:
http://forum.pdfsharp.net/viewtopic.php?p=2637#p2637

like image 52
I liked the old Stack Overflow Avatar answered Sep 21 '22 20:09

I liked the old Stack Overflow