PDFsharp编辑PDF文件

26

环境 - PDFsharp图书馆,使用Visual Studio 2012和C#语言。

我正在尝试:

  1. 读取宽度为17英寸,高度为11英寸,仅有1页的Test1.pdf文件
  2. 向其添加一些文本
  3. 将其另存为另一个文件(Test2.pdf)

我已经成功完成了以上所有操作。但当我打开Test2.pdf文件时,页面大小缩小为宽度为11英寸,高度为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");

1
尝试修改PDFNewDoc.Pages中的页面(而不是PDFDoc.Pages),或者使用AddPage()返回的页面。 - I liked the old Stack Overflow
我尝试运行这段代码,但它显示当前上下文中不存在PdfReader。 - Sudarshan Taparia
1个回答

16

PDFsharp团队,感谢您的回复。我会尝试按照这种方式重新构建我的代码,并再次联系您。 - Yuvi Dagar
PDFsharp团队,我已经重构了我的代码。我仍然遇到一些问题。请看一下我上面发布的重构代码。 - Yuvi Dagar
在遵循所有指示后,我成功解决了我的问题。非常感谢PDFsharp团队。 - Yuvi Dagar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接