Search code examples
c#pdfsharpmigradoc

MigraDoc: Rendering the same document twice


I want to render a "Document"-object twice, but on the second generation the PDF-File shows an error:

Error on this page. Maybe this page couldn't appear correctly. Please talk to the document-creator.

enter image description hereSorry, it is german...

This is my example-code:

using System;
using System.Windows.Forms;
using MigraDoc.Rendering;
using MigraDoc.DocumentObjectModel;
using PdfSharp.Pdf;
using System.Diagnostics;

namespace Temp
{
    public partial class Form1 : Form
    {
        Document document; //using the same document- and renderer-object ..
        PdfDocumentRenderer renderer; //..creates the error

        public Form1()
        {
            InitializeComponent();
            document = new Document();
            renderer = new PdfDocumentRenderer(false, PdfFontEmbedding.Always);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Section section = document.AddSection();
            Paragraph paragraph = section.AddParagraph();
            paragraph.AddFormattedText("Hello World", TextFormat.Bold);

            SaveFile(renderer);
        }

        private void SaveFile(PdfDocumentRenderer renderer)
        {
            renderer.Document = document;
            renderer.RenderDocument();
            string pdfFilename = string.Format("Rekla-{0:dd.MM.yyyy_hh-mm-ss}.pdf", DateTime.Now);
            renderer.PdfDocument.Save(pdfFilename);
            Process.Start(pdfFilename);
        }
    }
}

Of course i could always create a new "Document"-object:

private void button1_Click(object sender, EventArgs e)
{
    Document document = new Document(); //Creating a new document-object solves the problem..
    PdfDocumentRenderer renderer = new PdfDocumentRenderer(false, PdfFontEmbedding.Always);
    Section section = document.AddSection();
    Paragraph paragraph = section.AddParagraph();
    paragraph.AddFormattedText("Hi", TextFormat.Bold);

    SaveFile(renderer, document);
}

This works. But i need to change the current document while performing other button-click-events. The second code-snippet doesn't solve this task.

Does someone know how to fix the first code-snippet?


Solution

  • Do not re-use the Renderer. Create a new Renderer in the SaveFile method and everything should be fine.

    If a new Renderer is not enough, call document.Clone() and assign that to the Renderer.