使用 PDFSharp(1.50 或 6.1.0 Preview 2)我尝试打开现有的 pdf,添加一些文本,然后再次保存。
但是在绘制文本的行我收到了 System.ArgumentException
"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);
}
}
}
堆栈跟踪:
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)
更新:
我发现,如果我开始使用的 PDF 完全是空的或仅包含形状,则上述代码可以工作。
如果 PDF 已仅包含一段文本,则会触发此异常。那么这可能是 PDFSharp 中的一个错误?
测试您的代码并在进行这些更改后工作正常:
XFontStyle.BoldItalic
为 XFontStyleEx.BoldItalic
这篇文章中的说明实现了
FileFontResolver
并从您的代码中调用它。Verdana-BoldItalic.ttf
复制到默认位置。我的 PdfShap 版本是 6.1.0-preview-2,我正在使用 .Net 5。