我正在使用PDFSharp(1.50或6.1.0 Preview 2)try 打开现有的pdf,添加一些文本,然后再次保存.
然而,在绘制文本的那一行,我得到了System. ArgumentResponse "An item with the same key has already been added."
我不明白这个错误想告诉我什么或如何解决它.
注释DrawString
行即可编写新的pdf,但如何将文本添加到PDF中?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PdfSharp;
using PdfSharp.Pdf.IO;
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using PdfSharp.Fonts;
namespace MakeAPDF
{
internal class Program
{
static void Main(string[] args)
{
const string outfilename = @"C:\Test\Out.pdf";
PdfDocument document = PdfReader.Open(@"C:\Test\In.pdf",PdfDocumentOpenMode.Modify);
// Get an XGraphics object for drawing
PdfPage page = document.Pages[0];
XGraphics gfx = XGraphics.FromPdfPage(page);
// Create a font
XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic);
// Draw the text
// This line triggers System.ArgumentException
// Message=An item with the same key has already been added.
gfx.DrawString("Hello, World!", font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);
// Save the document...
document.Save(outfilename);
}
}
}
STACKTRACE:
System.ArgumentException
HResult=0x80070057
Message=An item with the same key has already been added.
Source=mscorlib
StackTrace:
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at PdfSharp.Pdf.Advanced.PdfResourceMap.CollectResourceNames(Dictionary`2 usedResourceNames)
at PdfSharp.Pdf.Advanced.PdfResources.ExistsResourceNames(String name)
at PdfSharp.Pdf.Advanced.PdfResources.get_NextExtGStateName()
at PdfSharp.Pdf.Advanced.PdfResources.AddExtGState(PdfExtGState extGState)
at PdfSharp.Drawing.Pdf.PdfGraphicsState.RealizeFillColor(XColor color, Boolean overPrint, PdfColorMode colorMode)
at PdfSharp.Drawing.Pdf.PdfGraphicsState.RealizeBrush(XBrush brush, PdfColorMode colorMode, Int32 renderingMode, Double fontEmSize)
at PdfSharp.Drawing.Pdf.PdfGraphicsState.RealizeFont(XFont font, XBrush brush, Int32 renderingMode)
at PdfSharp.Drawing.Pdf.XGraphicsPdfRenderer.Realize(XFont font, XBrush brush, Int32 renderingMode)
at PdfSharp.Drawing.Pdf.XGraphicsPdfRenderer.DrawString(String s, XFont font, XBrush brush, XRect rect, XStringFormat format)
at PdfSharp.Drawing.XGraphics.DrawString(String text, XFont font, XBrush brush, XRect layoutRectangle, XStringFormat format)
UPDATE:
我发现,如果我开始使用的PDF完全空或仅包含形状,上述代码仍然有效.如果PDF仅包含一段文本,则会触发此异常.那么这可能是PDFSharp中的一个错误吗?
引发该问题的PDF可以从here下载.