如何在java中使用Itext将页眉和页脚添加到我的PDF中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19856583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:45:06  来源:igfitidea点击:

How to add Header and footer to my PDF using Itext in java

javaitext

提问by Navyah

I want to add a header image and page numbers as footer to my PDF file. How can I add header and footer to my PDF file using Itext?

我想将页眉图像和页码作为页脚添加到我的 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 ***************");
}
}

采纳答案by sgrillon

Footer Header utils:

页脚页眉实用程序:

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);
    }

}

Use HeaderFooterPageEvent:

使用 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);

EDIT (add image sample):

编辑(添加图像样本):

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);
}

回答by Bruno Lowagie

Please take a look at the official iText documentationbefore posting a question on StackOverflow. More specifically: check the examples for the keyword header / footer.

在 StackOverflow 上发布问题之前,请先查看官方 iText 文档。更具体地说:检查关键字header / footer的示例。

You'll find the MovieCountries1example that creates a PDF with a header that has page numbersPage 1 / 39, Page 2 / 39, etc.

您会发现MovieCountries1示例,该示例创建了一个带有页码PDF 的页眉,页码为Page 1 / 39、Page 2 / 39 等。

Use that example as inspiration. If you don't need a Page X of Yheader (or footer). You can use a more simple example, such as the one in the answer to How to add Header and Footer in dynamic pdf using iTextLibrary?(which was also inspired by one of the examples of my book).

使用该示例作为灵感。如果您不需要第 X 页的 Y页眉(或页脚)。您可以使用更简单的示例,例如如何使用 iTextLibrary 在动态 pdf 中添加页眉和页脚的答案中的示例?(这也受到我书中的一个例子的启发)。

回答by Angel Salvador Ayala Ochoa

 HeaderFooter event = new HeaderFooter();
  writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));
  writer.setPageEvent(event);

document itxt

文件文件

ejemplo example of PDF

PDF 的ejemplo 示例

回答by Qingyu Yan

I am using iText2. Although PdfPageEventHelper can solve it, HeaderFooter seems more easier. Make sure add HeaderFooter before document.open(), otherwise first page will not display it.

我正在使用 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);

回答by Yahini priya Raja

This may help you for adding header and footer using itext:

这可以帮助您使用以下方法添加页眉和页脚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);
  }
}

回答by Faizan Khan

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();