使用itext 7,我遵循了y教程的第x页-https://kb.itextpdf.com/home/it7kb/ebooks/itext-7-building-blocks/chapter-7-handling-events-setting-viewer-preferences-and-printer-properties#chapter7:手持通风口;设置ViewerPreferences和PrinterProperties解决%22pagexofy%22问题我们的要求是将页码放在右下角。我尝试了占位符和初始“第x页,共页”的x,y位置的变化,但没有得到正确的位置。如果总页数为3位数,则与“of”重叠。如果总页数为2位数-则“of”和“total”之间有空格。我如何定位它,以避免有额外的空格或重叠字符。这是密码-
...
...
float topMargin = 30;
float bottomMargin = topMargin + 20;
float rightMargin = topMargin;
float leftMargin = topMargin;
Document document = new Document(pdf, PageSize.A4);
document.setMargins(topMargin, rightMargin, bottomMargin, leftMargin);
...
..
PageXofY pageXofYEvent = new PageXofY(pdf, document);
pdf.addEventHandler(PdfDocumentEvent.START_PAGE, pageXofYEvent);
pageXofYEvent.writeTotal(pdf);
public class PageXofY implements IEventHandler
{
protected PdfFormXObject placeholder;
PdfFont font = ITextFonts.getWriterBaseFont();
protected float side = 20;
protected float x = 300;
protected float y = 30;
protected float space = 10f;
protected float descent = 3;
Document document;
float pWidth = 0;
public PageXofY(PdfDocument pdf, Document document)
{
placeholder = new PdfFormXObject(new Rectangle(-20, -15, 100, 100));
this.document = document;
}
@Override
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 pdfCanvas = new PdfCanvas(page.getLastContentStream(), page.getResources(), pdf);
Canvas canvas = new Canvas(pdfCanvas, pdf, pageSize);
Paragraph p = new Paragraph().add("Page ").add(String.valueOf(pageNumber)).add(" of ")
.setFont(font).setFontSize(8).setMarginTop(10f);
pWidth = TableColumnSpacer.getParagraphWidth(p, document);
x = pageSize.getRight() - document.getRightMargin() - pWidth - 4f;
y = pageSize.getBottom() + 30 ;//document.getBottomMargin();
canvas.showTextAligned(p, x, y, TextAlignment.LEFT, VerticalAlignment.BOTTOM);
pdfCanvas.addXObjectAt(placeholder, x - space , y - 18);
pdfCanvas.release();
}
public void writeTotal(PdfDocument pdf)
{
Canvas canvas = new Canvas(placeholder, pdf);
Paragraph p = new Paragraph(String.valueOf(pdf.getNumberOfPages())).setFont(font).setFontSize(8).setMarginTop(10f);
canvas.showTextAligned(p, 30, descent, TextAlignment.LEFT, VerticalAlignment.BOTTOM);
}
}
1条答案
按热度按时间ni65a41a1#
通过在生成整个文档后添加页脚解决了此问题。迭代页面并添加页脚文本和第x页(共y页)。这是密码-