Error merging two PDF files using PDFsharp

浪尽此生 提交于 2020-01-17 05:06:34

问题


I am getting a problem when merging two files. If I try to have the AddPage(from.Pages[i]); in a separate void function I get

An object reference is required for the non-static field, method, or property It relates to CopyPages(one, outPdf); CopyPages(two, outPdf);

If I make it a static void it will run but the console displays an error stating that it "can not save a PDF with no pages"

static void Main(string[] args)
{

    PdfDocument one = new PdfDocument("1.pdf");
    PdfDocument two = new PdfDocument("2.pdf");
    PdfDocument outPdf = new PdfDocument();
    {
        CopyPages(one, outPdf);
        CopyPages(two, outPdf);
        outPdf.Save(out.pdf);
    }

}

void CopyPages(PdfDocument from, PdfDocument to)
{
    for (int i = 0; i < from.PageCount; i++)
    {
        to.AddPage(from.Pages[i]);
    }
}

回答1:


Your one is an empty PdfDocument, your two is an empty PdfDocument, the for loop does nothing, and outPdf is an empty PdfDocument.

As always, the computer does what you tell him to do. You can easily see that if you step through your code in a Debugger.

You have to use something like PdfDocument inputDocument = PdfReader.Open(file, PdfDocumentOpenMode.Import); to open a PDF file for import.

See also:
http://www.pdfsharp.net/wiki/ConcatenateDocuments-sample.ashx

new PdfDocument("1.pdf"); does not open/read a file, it just prepares the creation of a new file with that name.



来源:https://stackoverflow.com/questions/32756544/error-merging-two-pdf-files-using-pdfsharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!