我想在我的PDF文件中添加标题图片和页码作为页脚。如何使用Itext将页眉和页脚添加到我的PDF文件?
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Header;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class Demo {
/**
* @param args
*/
public static void main(String[] args) {
new Demo().createPDF();
}
public void createPDF(){
Document document = new Document (PageSize.A4);
try {
PdfWriter.getInstance(document, new FileOutputStream("C:/Documents and Settings/mnavya/Desktop/AddImage.pdf"));
document.open ();
document.addCreator("Binod by Demo.java");
document.addAuthor("Binod Suman");
document.addTitle("First PDF By Binod");
Image image = Image.getInstance("https://snaplogic-h.s3.amazonaws.com/uploads/partner/logo/24/stratappa.jpg?u=1382443264");
image.scaleAbsolute(50,50);
document.add(image);
Paragraph paragraph = new Paragraph(
" Factors",new Font(Font.FontFamily.HELVETICA, 25));
document.add(paragraph);
document.add(Chunk.SPACETABBING);
PdfPTable table = new PdfPTable(8);
table.setWidthPercentage(100);
float[] columnWidths = new float[] { 7, 20, 9, 9, 9, 9, 5, 3 };
table.setWidths(columnWidths);
PdfPCell cell = new PdfPCell();
cell.setColspan(8);
cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
table.addCell(cell);
table.addCell(" ");
table.addCell(" ");
table.addCell("");
table.addCell("");
table.addCell("%");
table.addCell("");
table.addCell(" ");
table.addCell(" ");
document.add(table);
document.close ();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
System.out.println("******** PDF Created ***************");
}
}
答案 0 :(得分:16)
页脚标题工具:
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
public class HeaderFooterPageEvent extends PdfPageEventHelper {
public void onStartPage(PdfWriter writer, Document document) {
ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("Top Left"), 30, 800, 0);
ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("Top Right"), 550, 800, 0);
}
public void onEndPage(PdfWriter writer, Document document) {
ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("http://www.xxxx-your_example.com/"), 110, 30, 0);
ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("page " + document.getPageNumber()), 550, 30, 0);
}
}
使用HeaderFooterPageEvent:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Document document = new Document(PageSize.A4, 20, 20, 50, 25);
PdfWriter writer = PdfWriter.getInstance(document, baos);
HeaderFooterPageEvent event = new HeaderFooterPageEvent();
writer.setPageEvent(event);
编辑(添加图片示例):
public void onStartPage(PdfWriter writer, Document document) {
String img = APPLICATION_SERVER_ROOT_PATH + File.separator + "assets" + File.separator + "images" + File.separator + "logo-tp-white.png";
Image image;
try {
image = Image.getInstance(img);
image.setAlignment(Element.ALIGN_RIGHT);
image.setAbsolutePosition(20, 790);
image.scalePercent(7.5f, 7.5f);
writer.getDirectContent().addImage(image, true);
} catch (IOException | DocumentException e) {
log.error("L'image logo-tp-50x50.png a provoqué une erreur.", e);
}
ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(""), 30, 800, 0);
ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(Constants.GLOBAL_HOST + " pour réussir votre prochain concours."), 400, 800, 0);
}
答案 1 :(得分:4)
HeaderFooter event = new HeaderFooter();
writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));
writer.setPageEvent(event);
ejemplo example of PDF
答案 2 :(得分:3)
在StackOverflow上发布问题之前,请先查看the official iText documentation。更具体地说:检查关键字header / footer的示例。
您会找到MovieCountries1创建PDF with a header that has page numbers Page 1/39,第2页/共39页等的示例。
使用该示例作为灵感。如果您不需要 Y页面的页眉(或页脚)。您可以使用一个更简单的示例,例如How to add Header and Footer in dynamic pdf using iTextLibrary?答案中的示例(其灵感来自我的书中的一个示例)。
答案 3 :(得分:0)
我正在使用iText2。 虽然PdfPageEventHelper可以解决它,但HeaderFooter似乎更容易。 确保在document.open()之前添加HeaderFooter,否则第一页将不会显示它。
Document document = new Document(PageSize.A4, MARGIN, MARGIN, MARGIN, MARGIN);
HeaderFooter footer = new HeaderFooter(new Phrase("- "), new Phrase(" -"));
footer.setAlignment(Element.ALIGN_CENTER);
footer.setBorder(Rectangle.NO_BORDER);
document.setFooter(footer);
答案 4 :(得分:0)
这可以帮助您使用itext
添加页眉和页脚:
public class PageNumber extends PdfPageEventHelper{
private PdfTemplate t;
private Image total;
public void onOpenDocument(PdfWriter writer, Document document) {
t = writer.getDirectContent().createTemplate(30, 16);
try {
total = Image.getInstance(t);
total.setRole(PdfName.ARTIFACT);
} catch (DocumentException de) {
throw new ExceptionConverter(de);
}
}
@Override
public void onEndPage(PdfWriter writer, Document document) {
addHeader(writer);
addFooter(writer);
}
private void addHeader(PdfWriter writer){
PdfPTable header = new PdfPTable(1);
try {
// set defaults
header.setWidths(new int[]{100});
header.setTotalWidth(525);
header.setLockedWidth(true);
header.getDefaultCell().setFixedHeight(65);
header.getDefaultCell().setBorder(Rectangle.BOTTOM);
header.getDefaultCell().setBorderColor(BaseColor.LIGHT_GRAY);
// add image
Image logo = Image.getInstance(PageNumber.class.getResource("/sample.png"));
header.addCell(logo);
// write content
header.writeSelectedRows(0, -1, 34, 823, writer.getDirectContent());
} catch(DocumentException de) {
throw new ExceptionConverter(de);
} catch (MalformedURLException e) {
throw new ExceptionConverter(e);
} catch (IOException e) {
throw new ExceptionConverter(e);
}
}
private void addFooter(PdfWriter writer){
PdfPTable footer = new PdfPTable(1);
try {
footer.setWidths(new int[]{100});
footer.setTotalWidth(527);
footer.setLockedWidth(false);
footer.getDefaultCell().setFixedHeight(40);
footer.getDefaultCell().setBorder(Rectangle.TOP);
footer.getDefaultCell().setBorderColor(BaseColor.LIGHT_GRAY);
// add current page count
footer.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
footer.addCell(new Phrase(String.format( writer.getPageNumber()+ " | Page") , new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD)));
// write page
PdfContentByte canvas = writer.getDirectContent();
canvas.beginMarkedContentSequence(PdfName.ARTIFACT);
footer.writeSelectedRows(0, -1, 34, 50, canvas);
canvas.endMarkedContentSequence();
} catch(DocumentException de) {
throw new ExceptionConverter(de);
}
}
public void onCloseDocument(PdfWriter writer, Document document) {
int totalLength = String.valueOf(writer.getPageNumber()).length();
int totalWidth = totalLength * 5;
ColumnText.showTextAligned(t, Element.ALIGN_LEFT,
new Phrase(String.valueOf(writer.getPageNumber()),new Font(Font.FontFamily.HELVETICA, 12)),
totalWidth, 6, 0);
}
}
答案 5 :(得分:0)
HeaderFooter header =new HeaderFooter(new Phrase(resources.getMessage("your header")),false);
header.setAlignment(HeaderFooter.ALIGN_CENTER);
header.setBorder(Rectangle.NO_BORDER);
document.setHeader(header);
document.open();