【问题标题】:PDFsharp edit a pdf filePDFsharp 编辑 pdf 文件
【发布时间】:2013-07-12 22:35:55
【问题描述】:

环境 - PDFsharp 库、Visual Studio 2012 和 C# 作为语言。

我正在尝试:

  1. 阅读 Test1.pdf(宽 = 17 英寸,高 - 11 英寸),一页
  2. 添加一些文字
  3. 另存为另一个文件(Test2.pdf)

我能够做以下所有事情。但是当我打开文件 Test2.pdf 时,页面的大小会减小到 Width = 11 英寸,Height – 11 英寸。 我使用的这些 PDF 文件是我从互联网上下载的产品规格表。我相信这只发生在某些类型的文件上,我不确定如何区分这些文件。

代码如下:

//File dimentions - Width = 17 inches, Height - 11 inches (Tabloid Format)
PdfDocument pdfDocument = PdfReader.Open(@"D:\Test1.pdf", PdfDocumentOpenMode.Modify);

PdfPage page = pdfDocument.Pages[0];
XGraphics gfx = XGraphics.FromPdfPage(page);
XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic);
gfx.DrawString("Hello, World!", font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);

//When the file is saved dimentions change to - Width = 11 inches, Height - 11 inches
pdfDocument.Save(@"D:\Test2.pdf");

我已经把文件上传到这里Test1.pdf

================================================ ====================================

根据 PDFsharp 团队的建议,代码应如下所示:

PdfDocument PDFDoc = PdfReader.Open(@"D:\Test1.pdf", PdfDocumentOpenMode.Import);
PdfDocument PDFNewDoc = new PdfDocument();

for (int Pg = 0; Pg < PDFDoc.Pages.Count; Pg++)
{
    PdfPage pp = PDFNewDoc.AddPage(PDFDoc.Pages[Pg]);

    XGraphics gfx = XGraphics.FromPdfPage(pp);
    XFont font = new XFont("Arial", 10, XFontStyle.Regular);
    gfx.DrawString("Hello, World!", font, XBrushes.Black, new XRect(0, 0, pp.Width, pp.Height), XStringFormats.BottomCenter);
}

PDFNewDoc.Save(@"D:\Test2.pdf");

【问题讨论】:

  • 尝试从 PDFNewDoc.Pages(不是 PDFDoc.Pages)修改页面 - 或获取 AddPage() 返回的页面。
  • 我尝试运行此代码。它说 PdfReader 在当前上下文中不存在?

标签: c#-4.0 pdf pdfsharp


【解决方案1】:

请不要修改文档,而是创建一个新文档并将旧文档中的页面复制到新文档中。

可以在 PDFsharp 论坛上的这篇帖子中找到示例代码:
http://forum.pdfsharp.net/viewtopic.php?p=2637#p2637

【讨论】:

  • PDFsharp 团队,感谢您的回复。我将尝试以这种方式重组我的代码并重新开始。
  • PDFsharp 团队,我已经重组了我的代码。我仍然面临一些问题。请看一下我上面发布的重组代码。
  • 按照所有说明操作后,我能够解决我的问题。非常感谢 PDFsharp 团队。
猜你喜欢
  • 2012-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-31
  • 2012-11-14
  • 2011-06-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多