Error merging two PDF files using PDFsharp
Asked Answered
F

1

0

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]);
    }
}
Fowliang answered 24/9, 2015 at 8:16 Comment(0)
T
3

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.

Thermosphere answered 24/9, 2015 at 8:37 Comment(1)
I hang my head in shame. Thank youFowliang

© 2022 - 2024 — McMap. All rights reserved.