Popplar
Popplar

Reputation: 279

PDFsharp asking for a PDF to be opened for Import when adding pages

I have 3 PDFs, I want to add the pages from them to an output PDF file. What I’m trying to do is: import first PDF -> create new PDF document -> add pages -> draw in certain page and finally I want to add the pages from that document to the main PDF document that will be exported. Proceed to do the same with the second PDF file if needed.

ERROR: A PDF document must be opened with PdfDocumentOpenMode.Import to import pages from it.

From the main class I call the method that processes the PDF:

        Pdftest pdftest = new Pdftest();
        PdfDocument pdf = PdfReader.Open(@"C:\Users\pdf_file.pdf", PdfDocumentOpenMode.Import);
        pdftest.CreatePages(pdf_file);

Pdftest class:

public class Pdftest
{
    PdfDocument PDFNewDoc = new PdfDocument();
    XFont fontChico = new XFont("Verdana", 8, XFontStyle.Bold);
    XFont fontGrande = new XFont("Verdana", 12, XFontStyle.Bold);
    XBrush fontBrush = XBrushes.Black;

    public void CreatePages(PdfDocument archivoPdf)
    {
        PdfDocument NuevoDoc = new PdfDocument();

        for (int Pg = 0; Pg < archivoPdf.Pages.Count; Pg++)
        {
            PdfPage pp = NuevoDoc.AddPage(archivoPdf.Pages[Pg]);
        }

        XGraphics Graficador = XGraphics.FromPdfPage(NuevoDoc.Pages[0]);

        XPoint coordinate = new XPoint();
        coordinate.X = XUnit.FromInch(1.4);
        coordinate.Y = XUnit.FromInch(1.8);

        graficador.DrawString("TEST", fontChico, fontBrush, coordinates);

        for (int Pg = 0; Pg < NuevoDoc.Pages.Count; Pg++)
        {
            PdfPage pp = PDFNewDoc.AddPage(NuevoDoc.Pages[Pg]); //Error mentioned.
        }
    }
 }

Upvotes: 3

Views: 3660

Answers (1)

The error message relates to NuevoDoc. You have to save NuevoDoc in a MemoryStream and re-open it in Import mode to get your code going.

I do not understand why you try to copy pages from NuevoDoc to PDFNewDoc- so most likely you can avoid the MemoryStream when optimising the code.

Upvotes: 2

Related Questions