I'm creating a pdf with iText 5 and want to add a footer. I did everything like the book "iText in action" in Chapter 14 says.
There are no errors but the footer doesn't show up.
Can somebody tell me what I'm doing wrong?
My code:
public class PdfBuilder {
private Document document;
public void newDocument(String file) {
document = new Document(PageSize.A4);
writer = PdfWriter.getInstance(document, new FileOutputStream(file));
MyFooter footerEvent = new MyFooter();
writer.setPageEvent(footerEvent);
document.open();
...
document.close();
writer.flush();
writer.close();
}
class MyFooter extends PdfPageEventHelper {
public void onEndPage(PdfWriter writer, Document document) {
PdfContentByte cb = writer.getDirectContent();
ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footer(), (document.right() - document.left()) / 2
+ document.leftMargin(), document.top() + 10, 0);
}
private Phrase footer() {
Font ffont = new Font(Font.FontFamily.UNDEFINED, 5, Font.ITALIC);
Phrase p = new Phrase("this is a footer");
return p;
}
}
The problem you report can not be reproduced. I have taken your example and I create the TextFooter example with this event:
class MyFooter extends PdfPageEventHelper {
Font ffont = new Font(Font.FontFamily.UNDEFINED, 5, Font.ITALIC);
public void onEndPage(PdfWriter writer, Document document) {
PdfContentByte cb = writer.getDirectContent();
Phrase header = new Phrase("this is a header", ffont);
Phrase footer = new Phrase("this is a footer", ffont);
ColumnText.showTextAligned(cb, Element.ALIGN_CENTER,
header,
(document.right() - document.left()) / 2 + document.leftMargin(),
document.top() + 10, 0);
ColumnText.showTextAligned(cb, Element.ALIGN_CENTER,
footer,
(document.right() - document.left()) / 2 + document.leftMargin(),
document.bottom() - 10, 0);
}
}
Note that I improved the performance by creating the Font and Paragraph instance only once. I also introduced a footer and a header. You claimed you wanted to add a footer, but in reality you added a header.
The top() method gives you the top of the page, so maybe you meant to calculate the y position relative to the bottom() of the page.
There was also an error in your footer() method:
private Phrase footer() {
Font ffont = new Font(Font.FontFamily.UNDEFINED, 5, Font.ITALIC);
Phrase p = new Phrase("this is a footer");
return p;
}
You define a Font named ffont, but you don't use it. I think you meant to write:
private Phrase footer() {
Font ffont = new Font(Font.FontFamily.UNDEFINED, 5, Font.ITALIC);
Phrase p = new Phrase("this is a footer", ffont);
return p;
}
Now when we look at the resulting PDF, we clearly see the text that was added as a header and a footer to each page.
By using showTextAligned method of PdfContentByte We can add footer to our page. Instead of phrase we should pass footer content as string to showTextAligned method as one of the parameter. If you want to format your footer content do before passing it to the method. Below is the sample code.
PdfContentByte cb = writer.getDirectContent();
cb.showTextAligned(Element.ALIGN_CENTER, "this is a footer", (document.right() - document.left()) / 2 + document.leftMargin(), document.bottom() - 10, 0);
Related
How to add an external link in PDF and redirect to the webpage.
.
.
.
example image describe below
On click on Goolge,user should redirect to webpage https://www.google.com
here is my code
private void createPDFiText() {
int margin = getResources().getDimensionPixelSize(R.dimen._5sdp);
Document document = new Document(PageSize.A4, margin, margin, margin, margin);
try {
PdfWriter.getInstance(document, getOutputStream());
document.open();
for (int i = 12; i <= 17; i++) {
Phrase phrase = new Phrase("Open ");
Phrase phrase1 = new Phrase(" on Click On it.");
Font anchorFont = new Font(Font.FontFamily.UNDEFINED, 25);
anchorFont.setColor(BaseColor.BLUE);
anchorFont.setStyle(Font.FontStyle.UNDERLINE.getValue());
Anchor anchor = new Anchor("Google", anchorFont);
anchor.setReference("www.google.com");
phrase.add(anchor);
phrase.add(phrase1);
document.add(phrase);
}
document.close();
} catch (DocumentException | IOException e) {
e.printStackTrace();
}
}
I am referring to this answer. Have a look. Modifying existing pdf file using iText 5.5.13.2 is complicated. But the referred solution is more easier.
iText 7 has handier way to modify existing pdf.
There are several other ways. Like PdfStamper etc.
From referred answer, add following code to make an anchor.
Phrase phrase = new Phrase("Open ");
Phrase phrase1 = new Phrase(" on Click On it.");
Font anchorFont = new Font(Font.FontFamily.UNDEFINED, 11);
anchorFont.setColor(BaseColor.BLUE);
anchorFont.setStyle(Font.FontStyle.UNDERLINE.getValue());
Anchor anchor = new Anchor("Google", anchorFont);
anchor.setReference("www.google.com");
phrase.add(anchor);
phrase.add(phrase1);
document.add(phrase);
Change the font and colors based on your needs.
Full code:
try {
PdfReader reader = new PdfReader("test.pdf"); //src pdf path (the pdf I need to modify)
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("test2.pdf")); // destination pdf path
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfImportedPage page = writer.getImportedPage(reader, 1);
document.newPage();
document.setPageSize(reader.getPageSize(1));
cb.addTemplate(page, 0, 0);
Phrase phrase = new Phrase("Open ");
Phrase phrase1 = new Phrase(" on Click On it.");
Font anchorFont = new Font(Font.FontFamily.UNDEFINED, 11);
anchorFont.setColor(BaseColor.BLUE);
anchorFont.setStyle(Font.FontStyle.UNDERLINE.getValue());
Anchor anchor = new Anchor("Google", anchorFont);
anchor.setReference("https://www.google.com");
phrase.add(anchor);
phrase.add(phrase1);
document.add(phrase);
document.close();
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
I am using itextsharp v 5.5.13 to create PDF documents.
One scenario where I need help is where the PDF document has a structure (header, body and footer like a template). The idea is to populate data only in the body section. Whenever there is overflow of data to next page, the data goes into the body of the next page maintaining the same structure (i.e. with header and footer).
Currently, I am able to achieve the same by creating pageeventhelper where on page start and page end, I am adding the header and footer. With this approach, I am able to get the desired result but it appears to be little hacky, and the appearance is also not that great (white spaces , gaps etc).
Any suggestions of a better way to handle this use case?
The code looks like as follows,
in the PdfPageEventHelper i have two different headers for page 1 and page 2, and a footer,
protected PdfPTable primaryHeader;
protected PdfPTable secondaryHeader;
protected PdfPTable footer;
public void setPrimaryHeader(PdfPTable header)
{
this.primaryHeader = header;
}
public void setSecondaryHeader(PdfPTable header)
{
this.secondaryHeader = header;
}
public void setFooter(PdfPTable footer)
{
this.footer = footer;
}
public override void OnStartPage(PdfWriter writer, Document document)
{
base.OnStartPage(writer, document);
if (writer.PageNumber == 1)
{
this.primaryHeader.TotalWidth = document.Right - document.Left;
this.primaryHeader.WriteSelectedRows(0, -1, 10, document.Top + 40, writer.DirectContent);
// Adding extra space to remove overlap of text
document.Add(PdfHelper.GetEmptyTable(200f));
}
else
{
this.secondaryHeader.TotalWidth = document.Right - document.Left;
this.secondaryHeader.WriteSelectedRows(0, -1, 10, document.Top + 40, writer.DirectContent);
// Adding extra space to remove overlap of text
document.Add(PdfHelper.GetEmptyTable(60f));
}
}
public override void OnEndPage(PdfWriter writer, Document document)
{
base.OnEndPage(writer, document);
this.footer.TotalWidth = document.Right - document.Left;
this.footer.WriteSelectedRows(0, -1, 10, document.Bottom + 10, writer.DirectContent);
}
The following code creates the byte array pdf,
using (MemoryStream stream = new MemoryStream())
{
Document document = new Document(PageSize.A4, 10, 10, 42, 35);
PdfWriter writer = PdfWriter.GetInstance(document, stream);
CustomPageEventHelper peh = new CustomPageEventHelper(true);
peh.setPrimaryHeader(GetPrimaryHeader(response, identity));
peh.setSecondaryHeader(GetSecondaryHeader(response, identity));
peh.setFooter(GetFooter(response, identity));
writer.PageEvent = peh;
document.Open();
PdfPTable table = null;
PdfPTable tableOuter = null;
PdfPTable tableInner = null;
PdfPTable tableGrid = null;
PdfPCell cell = null;
// Adding content here via PdfPTable's
document.Close();
result = stream.ToArray();
}
The following is the output,
Hi When I am generating form using java with itext I want to add form number on top left of the document
above the header.Please let me know the ways to do it.
PdfPTable table = new PdfPTable(3); // 3 columns.
table.setWidthPercentage(100);
PdfPCell cell1 = new PdfPCell(new Paragraph("Cell 1"));
PdfPCell cell2 = new PdfPCell(new Paragraph("Cell 2"));
PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 3"));
cell1.setBorder(0);
cell2.setBorder(0);
cell3.setBorder(0);
table.addCell(cell1);
table.addCell(cell2);
table.addCell(cell3);
How can I set the table alignment to start of the page margin.
Your question is very confusing. You say you are creating a form, but when you say form, you don't seem to be referring to an interactive form, but to an ordinary PDF containing a table.
You say you want to add a number above the header, but you are not telling us what you mean by header. You are assuming that the people reading your question can read your mind.
I guess you want to use a page event to add a String in the top left corner of each page. That would make your question almost a duplicate of itextsharp: How to generate a report with dynamic header in PDF using itextsharp?
You can create a subclass of PdfPageEventHelper like this:
public class Header extends PdfPageEventHelper {
protected Phrase header;
public void setHeader(Phrase header) {
this.header = header;
}
#Override
public void onEndPage(PdfWriter writer, Document document) {
PdfContentByte canvas = writer.getDirectContentUnder();
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, header, 36, 806, 0);
}
}
You can then use this Header class like this:
public void createPdf(String filename) throws IOException, DocumentException {
// step 1
Document document = new Document();
// step 2
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
Header event = new Header();
writer.setPageEvent(event);
// step 3
document.open();
// step 4
List<Integer> factors;
for (int i = 2; i < 301; i++) {
factors = getFactors(i);
if (factors.size() == 1) {
document.add(new Paragraph("This is a prime number!"));
}
for (int factor : factors) {
document.add(new Paragraph("Factor: " + factor));
}
event.setHeader(new Phrase(String.format("THE FACTORS OF %s", i)));
document.newPage();
}
// step 5
document.close();
}
In your case, you wouldn't have:
event.setHeader(new Phrase(String.format("THE FACTORS OF %s", i)));
You'd have something like:
event.setHeader(new Phrase(number));
Where number is the number you want to add at the coordinate x = 36, y = 806.
I have been searching the net on how to make or set a footer using itextpdf in java. and up until now i havent found anything on how to do it. I have seen some articles on how to use and set a header. but not footers. here's a sample code
Document document = new Document(PageSize.LETTER);
Paragraph here = new Paragraph();
Paragraph there = new Paragraph();
Font Font1 = new Font(Font.FontFamily.HELVETICA, 9, Font.BOLD);
here.add(new Paragraph("sample here", Font1));
there.add(new Paragraph("sample there", Font1));
//footer here
document.add(here);
document.add(there);
document.add(footer);
For implementing Header and footer you need to implement a HeaderFooter class that extends
PdfPageEventHelper class of iText API. Then override the onEndPage() to set header and footer. In this example I am settingname in header and 'page mumber` in footer.
In pdf creation side code you need to use HeaderAndFooter class like this:
Document document = new Document(PageSize.LETTER);
PdfWriter writer = PdfWriter.getInstance(document, "C:\sample.pdf");
//set page event to PdfWriter instance that you use to prepare pdf
writer.setPageEvent(new HeaderAndFooter(name));
.... //Add your content to documne here and close the document at last
/*
* HeaderAndFooter class
*/
public class HeaderAndFooter extends PdfPageEventHelper {
private String name = "";
protected Phrase footer;
protected Phrase header;
/*
* Font for header and footer part.
*/
private static Font headerFont = new Font(Font.COURIER, 9,
Font.NORMAL,Color.blue);
private static Font footerFont = new Font(Font.TIMES_ROMAN, 9,
Font.BOLD,Color.blue);
/*
* constructor
*/
public HeaderAndFooter(String name) {
super();
this.name = name;
header = new Phrase("***** Header *****");
footer = new Phrase("**** Footer ****");
}
#Override
public void onEndPage(PdfWriter writer, Document document) {
PdfContentByte cb = writer.getDirectContent();
//header content
String headerContent = "Name: " +name;
//header content
String footerContent = headerContent;
/*
* Header
*/
ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase(headerContent,headerFont),
document.leftMargin() - 1, document.top() + 30, 0);
/*
* Foooter
*/
ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT, new Phrase(String.format(" %d ",
writer.getPageNumber()),footerFont),
document.right() - 2 , document.bottom() - 20, 0);
}
}
Hope it helps. I had used this in one of the allication.
small demo with itextpdf 5
final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
final Document document = new Document();
final PdfContentByte cb = PdfWriter.getInstance(document, byteStream).getDirectContent();
final Paragraph footerTitleParagraph = new Paragraph();
footerTitleParagraph.add("footer title with no style");
ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footerTitleParagraph, document.right()/2, document.bottom()-15, 0);
final Paragraph footerSubTitleParagraph = new Paragraph("footer sub-title with style", FOOTER_FONT_SUB));
ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footerSubTitleParagraph, document.right()/2, document.bottom()-25, 0);
I'm trying to generate a pdf file using iText.
The file gets produced just fine, but I can seem to use special characters like german ä, ö, ...
The sentence I want to be written is (for example)
■ ...ä...ö...
but the output is
■...ä...ö...
(I had to kind of blur the sentences, but I guess you see what I'm talking about...)
Somehow this black block-thing and all "Umlaute" can't be generated ...
The font used is the following:
private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.BOLD);
So there should be no problem about the font not having these characters...
I'm using IntelliJ Idea to develop, the encoding of the .java file is set to UTF-8, so there should be no problem too...
I'm kind of lost here; does anyone know what i may do to get it working?
Thanks in advance and greetz
gilaras
---------------UPDATE---------------
So here's (part of) the code:
#Controller
public class Generator {
...
Font font = new Font(Font.FontFamily.TIMES_ROMAN, 9f, Font.BOLD);
...
Paragraph intro = new Paragraph("Ich interessiere mich für ...!", font_12_bold);
Paragraph wantContact = new Paragraph("■ Ich hätte gerne ... ", font);
...
Phrase south = new Phrase("■ Süden □ Ost-West ...");
...
#RequestMapping(value = "/generatePdf", method = RequestMethod.POST)
#ResponseBody
public String generatePdf(HttpServletRequest request) throws IOException, DocumentException, com.lowagie.text.DocumentException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(FILE));
addMetaData(document);
document.open();
addContent(document, request);
document.add(new Paragraph("äöü"));
document.close();
return "";
}
private void addContent(Document document, HttpServletRequest request)
throws DocumentException {
Paragraph preface = new Paragraph();
preface.setAlignment(Element.ALIGN_JUSTIFIED);
addEmptyLine(preface, 1);
preface.add(new Paragraph("Rückantwort", catFont));
addEmptyLine(preface, 2);
preface.add(intro);
addEmptyLine(preface, 1);
if (request.getParameter("dec1").equals("wantContact")) {
preface.add(wantContact);
} else {
...
}
document.add(preface);
}
private static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}
private static void addMetaData(Document document) {
document.addTitle("...");
document.addSubject("...");
document.addKeywords("...");
document.addAuthor("...");
document.addCreator("...");
}
}
I had to take some things out, but I kept some Umlaut-character and other special characters, so that you can see, where the problem occurs ... :-)
You might want to try and embed the font using this technique:
BaseFont times = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font font = new Font(times, 12, Font.BOLD);