How to open an existing PDF file with Migradoc PDF library
Asked Answered
A

1

6

I am trying to use the Migradoc library from PDFSharp (http://www.pdfsharp.net/) to print pdf files. So far I have found that Migradoc does support printing through its MigraDoc.Rendering.Printing.MigraDocPrintDocument class. However, I have not found a way to actually open an existing PDF file with MigraDoc.

I did find a way to open an existing PDF file using PDFSharp, but I cannot successfully convert a PDFSharp.Pdf.PdfDocument into a MigraDoc.DocumentObjectModel.Document object. So far I have not found the MigraDoc and PDFSharp documentation to be very helpful.

Does anyone have any experience using these libraries to work with existing PDF files?

I wrote the following code with help from this sample, but the result when my input PDF is 2 pages is an output PDF with 2 blank pages.

using MigraDoc.DocumentObjectModel;
using MigraDoc.Rendering;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;

...

public void PrintPDF(string filePath, string outFilePath)
{

    var document = new Document();

    var docRenderer = new DocumentRenderer(document);
    docRenderer.PrepareDocument();

    var inPdfDoc = PdfReader.Open(filePath, PdfDocumentOpenMode.Modify);

    for (var i = 0; i < inPdfDoc.PageCount; i++)
    {
        document.AddSection();
        docRenderer.PrepareDocument();

        var page = inPdfDoc.Pages[i];

        var gfx = XGraphics.FromPdfPage(page);

        docRenderer.RenderPage(gfx, i+1);
    }

    var renderer = new PdfDocumentRenderer();

    renderer.Document = document;

    renderer.RenderDocument();

    renderer.PdfDocument.Save(outFilePath);

}
Acquire answered 6/2, 2015 at 16:22 Comment(0)
S
2

Your code modifies the inPdfDoc in memory without saving the changes. Complicated code without any visual effect.

MigraDoc cannot open PDF files, MigraDoc cannot print PDF files, PDFsharp cannot print PDF files.

http://www.pdfsharp.net/wiki/PDFsharpFAQ.ashx

Soybean answered 7/2, 2015 at 6:19 Comment(2)
Why does it not save the changes? It looks like it should work: render pages into new document, then save document.Oyler
@AndreasReiff The parameter filePath is used to open a PDF file and to modify that file in memory without saving it. The parameter outFilePath is used to save a newly created document that does not contain anything from the input file. There is no "connection" between inPdfDoc and outFilePath`.Soybean

© 2022 - 2024 — McMap. All rights reserved.