我使用PDFsharp合并了2个PDF文件。我的代码将页码添加到每页的底部。现在,我需要以相同的方式将创建的文档与另一个PDF合并。我得到的问题是从上一个文档创建的零件上的页码很好。从第一个合并创建的文档的新页码已添加到第一组页面的顶部,因此,在第一组页面中现在彼此之间有两个页码。因此,我一眼就能同时看到“ 40页的第1页”和“ 110页的第1页”。
这是我用来合并PDF的代码
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
namespace SomeProject.Helpers
{
public static class PDFHelper
{
public static void MergePDFFiles(string[] pdfFiles, string outputFilePath)
{
PdfDocument document = new PdfDocument();
foreach (string pdfFile in pdfFiles)
{
PdfDocument inputPDFDocument = PdfReader.Open(pdfFile, PdfDocumentOpenMode.Import);
document.Version = inputPDFDocument.Version;
foreach (PdfPage page in inputPDFDocument.Pages)
{
document.AddPage(page);
}
}
// Set font for paging
XFont font = new XFont("Verdana", 9);
XBrush brush = XBrushes.Black;
// Create variable that store page count
string noPages = document.Pages.Count.ToString();
// Set for loop of document page count and set page number using DrawString function of PdfSharp
for (int i = 0; i < document.Pages.Count; ++i)
{
PdfPage page = document.Pages[i];
// Make a layout rectangle.
XRect layoutRectangle = new XRect(240 /*X*/ , page.Height - font.Height - 10 /*Y*/ , page.Width /*Width*/ , font.Height /*Height*/ );
using (XGraphics gfx = XGraphics.FromPdfPage(page))
{
gfx.DrawString("Page " + (i + 1).ToString() + " of " + noPages, font, brush, layoutRectangle, XStringFormats.Center);
}
}
document.Save(outputFilePath);
}
}
}
一种干净的解决方案:仅将页码添加到最终文档中。保留没有页码的中间文件副本,或根据需要两次创建文件。
hack:在新页码下方绘制一个白色矩形,以隐藏该区域中已经存在的所有内容。 PDF将具有两个页码,但是只有最新和当前的页码才可见。
删除页码有点复杂。