2013-07-15 102 views
13

環境 - PDFsharp庫,Visual Studio 2012和C#作爲語言。PDFsharp編輯pdf文件

我想:

  1. 讀Test1.pdf(寬= 17英寸,高度 - 11英寸)與1頁
  2. 一些文本添加到它
  3. 保存爲其他文件( Test2.pdf)

我能夠做到以下所有。但是當我打開Test2.pdf文件時,頁面的大小已經減小到寬度= 11英寸,高度 - 11英寸。 我正在使用的這些PDF文件是我從互聯網下載的產品規格表。我相信這隻發生在某些類型的文件上,我不確定如何區分這些文件。

代碼如下:

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

我已上載這裏的文件Test1.pdf

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

如所建議的由PDFsharp隊的代碼應該如下:

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"); 
+1

嘗試修改從PDFNewDoc.Pages(未PDFDoc.Pages)的頁面 - 或採取()由AddPage返回的頁面。 –

+0

我試過運行這段代碼。它說PdfReader在當前上下文中不存在? –

回答

8

而不是修改文檔,請創建一個新文檔,並將舊文檔中的頁面複製到新文檔。

示例代碼可以在這個崗位上PDFsharp論壇上找到:
http://forum.pdfsharp.net/viewtopic.php?p=2637#p2637

+0

PDFsharp團隊,感謝您的答覆。我將嘗試以這種方式重構我的代碼,然後重新開始。 –

+0

PDFsharp團隊,我重組了我的代碼。我仍然面臨一些問題。請看看我上面發佈的重組代碼。 –

+0

按照所有說明完成操作後,我能夠解決我的問題。非常感謝PDFsharp團隊。 –