2016-04-29 24 views
0

我之前使用PDFsharp進行了一些文件合併,現在我試圖更改多個文件(插入或移除一些頁面),並且遇到了問題,即庫看不到頁面。它說PageCount == 0,我無法在對象中找到頁面(在調試時)。當然,我不能做我目前的工作。我用這個非常簡單的代碼:PDFsharp沒有看到文檔中的頁面

var destinationPdf = new PdfDocument(destinationFilePath); 
Int32 count = destinationPdf.PageCount; 

而且也,這裏是代碼,我用以前的文件合併到一個PDF:

public class PdfCreator 
{ 
    private PdfDocument document; 

    public PdfCreator() 
    { 
     this.document = new PdfDocument(); 
    } 

    public void AddImage(String imageFilePath) 
    { 
     PdfPage newPage = this.document.AddPage(); 
     XGraphics xGraphics = XGraphics.FromPdfPage(newPage); 
     XImage image = XImage.FromFile(imageFilePath); 
     xGraphics.DrawImage(image, 0, 0); 
    } 

    public void AddPdfFile(String pdfFilePath) 
    { 
     PdfDocument inputDocument = PdfReader.Open(pdfFilePath, PdfDocumentOpenMode.Import); 
     Int32 count = inputDocument.PageCount; 
     for (Int32 currentPage = 0; currentPage < count; currentPage++) 
     { 
      PdfPage page = inputDocument.Pages[currentPage]; 
      this.document.AddPage(page); 
     } 
    } 

    public void AddTextFile(String txtFilePath) 
    { 
     PdfPage newPage = this.document.AddPage(); 
     XGraphics xGraphics = XGraphics.FromPdfPage(newPage); 
     var xFont = new XFont("Times New Roman", 12, XFontStyle.Bold); 
     var xTextFormatter = new XTextFormatter(xGraphics); 
     var rect = new XRect(30, 30, 540, 740); 
     xGraphics.DrawRectangle(XBrushes.Transparent, rect); 
     xTextFormatter.Alignment = XParagraphAlignment.Left; 
     xTextFormatter.DrawString(File.ReadAllText(txtFilePath), xFont, XBrushes.Black, rect, XStringFormats.TopLeft); 
    } 

    public void Save(String destinationFilePath) 
    { 
     if (this.document.Pages.Count > 0) 
     { 
      this.document.Save(destinationFilePath); 
      this.document.Close(); 
     } 
    } 
} 
+0

的可能的複製[錯誤使用合併兩個PDF文件PDFsharp(http://stackoverflow.com/questions/32756544/error-merging-two-pdf-files-using-pdfsharp) –

+0

@ThomasH這似乎因爲問題的原因和解決方案是相同的,但我確信,'症狀'是完全不同的。 – user2216

回答

3

您的代碼

var destinationPdf = new PdfDocument(destinationFilePath); 
Int32 count = destinationPdf.PageCount; 

創建記憶中的新文件 - 當然這個文件是空的。使用PdfReader.Open從現有文件在內存中創建文檔。

當我把鼠標光標放在PdfDocument在你的代碼中,我得到這個提示:

創建具有指定文件名的新的PDF文檔。該文件是 立即創建,並保持鎖定,直到文檔關閉,在 文件被自動保存。不要調用Save() 用此構造函數創建的文檔,只需調用Close()。要打開 現有PDF文件並將其導入,請使用PdfReader類。