我习惯用水印的代码如下所示。对于前两页,水印显示正确,但对于第三页,水印显示在左上角。当我调试时,它显示的页面大小约为692 * 712。
class Program
{
static string absoluteFile1Path = "filename1.pdf";
static string absoluteFile2Path = "filename2.pdf";
static string destination = "destinationfilename.pdf";
static void Main(string[] args)
{
string[] filesPath = new string[] { absoluteFile1Path, absoluteFile2Path };
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(destination));
PdfMerger merger = new PdfMerger(pdfDoc);
PdfDocument srcDoc1 = new PdfDocument(new PdfReader(absoluteFile1Path));
merger.Merge(srcDoc1, 1, srcDoc1.GetNumberOfPages());
PdfDocument srcDoc2 = new PdfDocument(new PdfReader(absoluteFile2Path));
merger.Merge(srcDoc2, 1, srcDoc2.GetNumberOfPages());
pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE, new WatermarkHandler());
srcDoc1.Close();
srcDoc2.Close();
pdfDoc.Close();
}
}
public class WatermarkHandler : IEventHandler
{
Color lime, blue;
PdfFont helvetica;
PdfFont font;
public WatermarkHandler()
{
//helvetica = PdfFontFactory.CreateFont(FontConstants.HELVETICA);
//lime = new DeviceCmyk(0.208f, 0, 0.584f, 0);
//blue = new DeviceCmyk(0.445f, 0.0546f, 0, 0.0667f);
font = PdfFontFactory.CreateFont(FontConstants.HELVETICA);
}
public void HandleEvent(Event @event)
{
PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
PdfDocument pdf = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
int pageNumber = pdf.GetPageNumber(page);
Rectangle pageSize = page.GetPageSize();
PdfCanvas canvas = new PdfCanvas(page.NewContentStreamAfter(), page.GetResources(), pdf);
PdfExtGState gs1 = new PdfExtGState().SetFillOpacity(0.9f).SetStrokeOpacity(0.3f);
canvas.SetExtGState(gs1);
new Canvas(canvas, pdf, new iText.Kernel.Geom.Rectangle(page.GetPageSize().GetWidth() / 2, page.GetPageSize().GetHeight() / 2))
.SetFontColor(iText.Kernel.Colors.DeviceGray.LIGHT_GRAY)
.SetFontSize(26)
.SetFont(font)
.ShowTextAligned(new Paragraph("FOR YOUR RECORDS ONLY: DO NOT SUBMIT"), 298, 375, pdf.GetPageNumber(page),
TextAlignment.CENTER, VerticalAlignment.MIDDLE, 45);
canvas.Release();
}
}
}
答案 0 :(得分:0)
如果没有看到pdf,我无法确定,但这很可能是由于其中一个页面被旋转(如果第3页的宽度和高度翻转,则为90度或270度),因此绝对坐标在旋转的页面上显示你的水印有点偏。
您可以使用PdfPage#getRotation()
获取页面的旋转,并根据检索到的值编写一些额外的逻辑来计算旋转的x和y。 There's some info on the coordinate system used in pdfs in chapter 2 of the iText7 jumpstart tutorial.