PDFsharp & MigraDoc Foundation
https://forum.pdfsharp.net/

Cannot write to existing page
https://forum.pdfsharp.net/viewtopic.php?f=2&t=2813
Page 1 of 1

Author:  Craigjb12 [ Fri May 16, 2014 5:35 pm ]
Post subject:  Cannot write to existing page

I've loaded an existing PDFDoc and created PDFNewDoc from it.
Quote:
PdfDocument PDFDoc = PdfReader.Open("c:/cards.pdf", PdfDocumentOpenMode.Import);
PdfDocument PDFNewDoc = new PdfDocument();


The below works just fine, it copies the original pages to the new doc.
Code:
            for (int Pg = 0; Pg < PDFDoc.Pages.Count; Pg++)
            {
                PdfPage page = PDFNewDoc.AddPage(PDFDoc.Pages[Pg]);
                XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append);     
            }
   


However, if I try to add to each page as I go...
Code:
            {
                PdfPage page = PDFNewDoc.AddPage(PDFDoc.Pages[Pg]);
                XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append);
               gfx.DrawString("Hello, World!", font, brush, new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);
            }


I get the error:
Quote:
A critical error has occurred. An item with the same key has already been added.


Below is the full code.

Code:
using System;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using System.Diagnostics;
using PdfSharp;
using PdfSharp.Pdf.IO;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using DotNetNuke.Entities.Modules;

namespace Clarity.PDF
{
    public partial class PDFGenerator : DotNetNuke.Entities.Modules.PortalModuleBase
    {

 
        protected void GeneratePDF(object sender, EventArgs e)
        {
            // Define Data
            string s1_firstname = LDR_firstname_1.Text.ToString();

            // Define paths
            string savename = "c:/HelloWorld3.pdf";
            string PreviewPath = "/HelloWorld3.pdf";

            // Define Brushes and Fonts
            XFont font = new XFont("Arial", 10, XFontStyle.Regular);
            XBrush brush = new XSolidBrush(XColor.FromArgb(128, 255, 0, 0));

            // Open existing document and create a new one
            PdfDocument PDFDoc = PdfReader.Open("c:/cards.pdf", PdfDocumentOpenMode.Import);
            PdfDocument PDFNewDoc = new PdfDocument();

            // Loop through pdfdoc and add each page to our new doc
            for (int Pg = 0; Pg < PDFDoc.Pages.Count; Pg++)
            {
                PdfPage page = PDFNewDoc.AddPage(PDFDoc.Pages[Pg]);
                XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append);
               gfx.DrawString("Hello, World!", font, brush, new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);
            }
         
            Preview.NavigateUrl = PreviewPath;
            PDFNewDoc.Save(savename);

        }

    }
}

Page 1 of 1 All times are UTC
Powered by phpBB® Forum Software © phpBB Group
https://www.phpbb.com/