环境 - PDFsharp图书馆,使用Visual Studio 2012和C#语言。
我正在尝试:
- 读取宽度为17英寸,高度为11英寸,仅有1页的Test1.pdf文件
- 向其添加一些文本
- 将其另存为另一个文件(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");