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);

}
Brian
  • 2,702
  • 5
  • 37
  • 71

1 Answers1

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

  • 1
    Why does it not save the changes? It looks like it should work: render pages into new document, then save document. – Andreas Reiff Sep 20 '17 at 06:04
  • 1
    @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`. – I liked the old Stack Overflow Sep 20 '17 at 17:56