IText : Add an image on a header with an absolute position - java

I want to place a header on each page of my PDF.
The text part of the header is done but I can't find a way to place an image.
public static class Header extends PdfPageEventHelper {
public void onEndPage(PdfWriter writer, Document document) {
try{
PdfContentByte cb = writer.getDirectContent();
/*
Some code to place my text in the header
*/
Image imgSoc = Image.getInstance("C:\\...\\Logo.jpg");
imgSoc.scaleToFit(110,110);
imgSoc.setAbsolutePosition(390, 720);
ColumnText ct = new ColumnText(cb);
ct.addText(new Chunk(imgSoc,0,0));
ct.go();
}catch(Exception e){
e.printStackTrace();
}
}
}
I'm not really sure I'm doing this the right way.

There already are two answers using tables.
Tables can be very helpful to create a dynamic layout of different header parts (document title, document version, page number, logo, ...).
But if you don't need that, already have everything in place like the OP has, you can simply add the image at a fixed position with a fixed size:
public static class Header extends PdfPageEventHelper {
public void onEndPage(PdfWriter writer, Document document) {
try
{
PdfContentByte cb = writer.getDirectContent();
/*
Some code to place some text in the header
*/
Image imgSoc = Image.getInstance("C:\\...\\Logo.jpg");
imgSoc.scaleToFit(110,110);
imgSoc.setAbsolutePosition(390, 720);
cb.addImage(imgSoc);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
PS: If you really use the same logo on all pages, you had better read the image file into an Image instance only once (e.g. in the constructor or onOpenDocument), hold that instance in a variable and re-use it again and again. This way you include the image data only once in the PDF.

A way to achieve this is to create the header as a table:
PdfPTable table = new PdfPTable(1);
Image imgSoc = Image.getInstance("C:\\...\\Logo.jpg");
imgSoc.scaleToFit(110,110);
PdfPCell cell = new PdfPCell(imgSoc , true);
cell.setBorder(0);
table.addCell(cell);
float[] columnWidths = new float[] { 100};
table.setWidthPercentage(100f);
table.setWidths(columnWidths);
ColumnText ct = new ColumnText(cb);
ct.addElement(table);
ct.setSimpleColumn(36, 0, 559, 806); //Position goes here
ct.go();

You could use iText Table in such a way that , you can show your logo either left or right depending upon the user choice.
Chunk header = new Chunk("your header text", headerFont);
Image logo = Image.getInstance("../../..");
// your image path
logo.scaleAbsolute(80f, 80f);
logo.scalePercent(100);
table = new PdfPTable(3);
table.setWidthPercentage(100);
PdfPCell detailCell = new PdfPCell(new Phrase(header));
detailCell.setBorder(Rectangle.NO_BORDER);
detailCell.setHorizontalAlignment(alignment);
detailCell.setVerticalAlignment(Element.ALIGN_TOP);
PdfPCell logoRightCell = new PdfPCell();
logoRightCell.setFixedHeight(80);
logoRightCell.setBorder(Rectangle.NO_BORDER);
logoRightCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
PdfPCell logoLeftCell = new PdfPCell();
logoLeftCell.setFixedHeight(80);
logoLeftCell.setBorder(Rectangle.NO_BORDER);
logoLeftCell.setHorizontalAlignment(Element.ALIGN_LEFT);
if (true) {
String logoAlign = "left";
if (logoAlign.compareTo("Left") == 0) {
logo.setAlignment(Element.ALIGN_LEFT);
logoLeftCell.addElement(logo);
} else {
logo.setAlignment(Element.ALIGN_RIGHT);
logoRightCell.addElement(logo);
}
}
String headerAlign = "Center";
if (headerAlign.compareTo("Center") == 0) {
table.setWidths(new int[] { 2, 7, 2 });
table.addCell(logoLeftCell);
table.addCell(detailCell);
table.addCell(logoRightCell);
} else if (headerAlign.compareTo("Left") == 0) {
table.setWidths(new int[] { 7, 2, 2 });
table.addCell(detailCell);
table.addCell(logoLeftCell);
table.addCell(logoRightCell);
} else {
table.setWidths(new int[] { 2, 2, 7 });
table.addCell(logoLeftCell);
table.addCell(logoRightCell);
table.addCell(detailCell);
}
//
table.setTotalWidth(document.getPageSize().getWidth()
- document.leftMargin() - document.rightMargin());
table.writeSelectedRows(0, -1, document.leftMargin(), document
.getPageSize().getHeight() - document.topMargin() + 20,
writer.getDirectContent());
}
document.add(table);

Related

How to put iText LIST on absolute position with certain font and alignment?

public void printTextOnAbsolutePosition(String teks, PdfWriter writer, Rectangle rectangle, boolean useAscender) throws Exception {
Font fontParagraf = new Font(Font.FontFamily.HELVETICA, 10, Font.NORMAL);
rectangle.setBorder(Rectangle.BOX);
rectangle.setBorderColor(BaseColor.RED);
rectangle.setBorderWidth(0.0f);
PdfContentByte cb = writer.getDirectContent();
cb.rectangle(rectangle);
Paragraph para = new Paragraph(teks, fontParagraf);
ColumnText columnText = new ColumnText(cb);
columnText.setSimpleColumn(rectangle);
columnText.setUseAscender(useAscender);
columnText.addText(para);
columnText.setAlignment(3);
columnText.setLeading(10);
columnText.go();
}
We can use the above code to print text with iText on absolute position. But how can we achieve the same with List? Also, how to format the text of the list so it uses certain font and text alignment?
public void putBulletOnAbsolutePosition(String yourText, PdfWriter writer, Float koorX, Float koorY, Float lebarX, Float lebarY) throws Exception {
List listToBeShown = createListWithBulletImageAndFormatedFont(yourText);
// ... (the same) ...
columnText.addElement(listToBeShown);
columnText.go();
}
The method is essentially the same. By looking at the documentation, we find that instead of using .addtext on ColumnText, we use .addElement which accept Paragraph, List, PdfPTable and Image.
As for formating the list text, we simply need to make paragraf as the input for the list (and not using columnText.setAlignment() to set the alignment).
public List createListWithBulletImageAndFormatedFont(String yourText) throws Exception {
Image bulletImage = Image.getInstance("src/main/resources/japoimages/bullet_blue_japo.gif");
bulletImage.scaleAbsolute(10, 8);
bulletImage.setScaleToFitHeight(false);
List myList = new List();
myList.setListSymbol(new Chunk(Image.getInstance(bulletImage), 0, 0));
String[] yourListContent = yourText.split("__");
Font fontList = new Font(Font.FontFamily.HELVETICA, 10, Font.NORMAL);
for (int i=0; i < yourListContent.length; i++) {
Paragraph para = new Paragraph(yourListContent[i], fontList);
para.setAlignment(Element.ALIGN_JUSTIFIED);
myList.add(new ListItem(para));
}
return myList;
}
The above codes will print bulleted list (using image) on any location we desire.
public void putBulletnAbsolutePosition (String dest) throws Exception {
Document document = new Document(PageSize.A5, 30,30, 60, 40);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
String myText = "ONE__TWO__THREE__FOUR";
putBulletOnAbsolutePosition(myText, writer, 140f, 350f, 300f, 200f);
document.close();
}

How to add header or footer using itextpdf only after first page in java?

I have written a java program to download a pdf , but I want to add header to that pdf document only after 1st page , I have tried some code.
class MyFooter extends PdfPageEventHelper {
Font ffont = new Font(Font.FontFamily.UNDEFINED, 10, Font.BOLD);
private void addHeader(PdfWriter writer,Document document){
PdfContentByte cb = writer.getDirectContent();
Phrase header = new Phrase("Customer Id : ", ffont);
ColumnText.showTextAligned(cb, Element.ALIGN_CENTER,
header,
(document.right() - document.left()) / 2 +
document.leftMargin(),
document.top() - 10, 0);
}
private void addFooter(PdfWriter writer,Document document){
PdfContentByte cb = writer.getDirectContent();
Phrase footer = new Phrase("Page "+writer.getPageNumber(),
ffont);
ColumnText.showTextAligned(cb, Element.ALIGN_CENTER,
footer,
(document.right() - document.left()) / 2 +
document.leftMargin(),
document.bottom() - 10, 0);
}
public void onEndPage(PdfWriter writer, Document document) {
try{
addHeader(writer,document);
addFooter(writer,document);
}catch(Exception e){
e.printStackTrace();
}
}
}
The footer function is working properly , but I want the header function to print only after 1st page, so I tried using
if(writer.getPageNumber() > 1)
but this condition is not working
Try
if (document.getPageNumber() > 1)
The page number in the writer is the page number of the PDF and will be there after writing the PDF.
Better to try this method
document.resetHeader();
after the execution of the first-page logic.

Use different Table Header on first page

I'm using iText and create a dynamic table which has a a reoccurring header in the method createTabularHeader:
PdfPTable table = new PdfPTable(6);
// fill it with some basic information
table.setHeaderRows(1);
Yet on the first page I would like to display different information. (but the table structure/size remains the same)
Due to the dynamic content which is obtained in a different method I can't say when a new page starts.
I tried with the most primitive variant - just adding a white rectangle over the text and insert the different text. As it's just on the first page all I have to do is creating that rectangle between both methods.
But the white rectangle doesn't have any opacity and can' cover anything.
Yet by trying around I found the method writer.getDirectContent().setColorStroke(BaseColor.WHITE); which set the text to white. Later I just set the BaseColor of my cells manually to black. But the even though the new text is applied after the calling of my createTabularHeader-method its layer is under the layer of the original text and the letters are covering the new text partly.
Using the answer to How to insert invisible text into a PDF? brought me to the idea of using myPdfContentByte.setTextRenderMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE); was not so helpful as it resets only on the 2nd page regardless what I do and the regular text on the first page stays invisible.
I'm unable to find a proper solution... How can the table-header be modified only on the first page?
The solution is not really nice, but works... and as some sort of bonus I want to add how you can modify the indentions on the first page.
public void createPdf() {
document = new Document();
try {
PdfWriter writer = PDFHead.getWriter(document);
//If it's a letter we have a different indention on the top
if (letterPDF) {
document.setMargins(36, 36, 100, 36);
} else {
document.setMargins(36, 36, 36, 36);
}
document.open();
document.add(createTabularContent());
document.close();
} catch (DocumentException | FileNotFoundException ex) {
try {
document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(FILENAME));
document.open();
document.add(new Phrase(ex.getLocalizedMessage()));
document.close();
Logger.getLogger(Etikette.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException | DocumentException ex1) {
Logger.getLogger(Etikette.class.getName()).log(Level.SEVERE, null, ex1);
}
}
}
The PDFHead is used to create a regular header (the one which appears on every page, not only on pages with the table):
public static PdfWriter getWriter(Document document) throws FileNotFoundException, DocumentException {
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
HeaderFooter event = new HeaderFooter("Ing. Mario J. Schwaiger", type + " " + DDMMYYYY.format(new java.util.Date()), 835, isLetterPDF(), customerNumber);
writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));
writer.setPageEvent(event);
return writer;
}
And in that HeaderFooter-Event I use the fact the function is called after the PDF is basically created (for the page number for instance):
#Override
public void onEndPage(PdfWriter writer, Document document) {
if (isLetter) {
//That's only for the first page, apparently 1 is too late
//I'm open for improvements but that works fine for me
if (writer.getPageNumber() == 0) {
//If it's a letter we use the different margins
document.setMargins(36, 36, 100, 36);
}
if (writer.getPageNumber() == 1) {
PdfContentByte canvas = writer.getDirectContent();
float llx = 460;
float lly = 742;
float urx = 36;
float ury = 607;
//As I add the rectangle in the event here it's
//drawn over the table-header. Seems the tableheader
//is rendered afterwards
Rectangle rect1 = new Rectangle(llx, lly, urx, ury);
rect1.setBackgroundColor(BaseColor.WHITE);
rect1.setBorder(Rectangle.NO_BORDER);
rect1.setBorderWidth(1);
canvas.rectangle(rect1);
ColumnText ct = new ColumnText(canvas);
ct.setSimpleColumn(rect1);
PdfPTable minitable = new PdfPTable(1);
PdfPCell cell = PDFKopf.getKundenCol(PDFHeader.getCustomer(customerNumber));
cell.setBorder(Rectangle.NO_BORDER);
minitable.addCell(cell);
//A single cell is not accepted as an "Element"
//But a table including only a single cell is
ct.addElement(minitable);
try {
ct.go();
} catch (DocumentException ex) {
Logger.getLogger(HeaderFooter.class.getName()).log(Level.SEVERE, null, ex);
}
//In any other case we reset the margins back to normal
//This could be solved in a more intelligent way, feel free
} else {
document.setMargins(36, 36, 36, 36);
}
}
//The regular header of any page...
PdfPTable table = new PdfPTable(4);
try {
table.setWidths(new int[]{16, 16, 16, 2});
table.setWidthPercentage(100);
table.setTotalWidth(527);
table.setLockedWidth(true);
table.getDefaultCell().setFixedHeight(20);
table.getDefaultCell().setBorder(Rectangle.BOTTOM);
table.addCell(header);
PdfPCell cell;
cell = new PdfPCell(new Phrase(mittelteil));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setBorder(Rectangle.BOTTOM);
table.addCell(cell);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
table.addCell(String.format("Page %d of ", writer.getPageNumber()));
cell = new PdfPCell(Image.getInstance(total));
cell.setBorder(Rectangle.BOTTOM);
table.addCell(cell);
table.writeSelectedRows(0, -1, 34, y, writer.getDirectContent());
} catch (DocumentException de) {
throw new ExceptionConverter(de);
}
}

Setting multi-line text to form fields in PDFBox

I'm using PDFBox to fill form fields in a pdf using below code:
PDField nameField = form.getField("name");
if(null != nameField){
nameField.setValue(data.get("name")); // data is a hashmap
nameField.setReadonly(true);
}
The problem is, if the text is long it doesn't split to multiple lines, even though I have enabled the "multi-line" option for the field in the pdf. Do I have to do anything from the code as well to enable this?
Thanks.
Remember
Setting the ressources for the fonts to be used into the TextField.
Associating the ressources with the PDAccroform of the PDDocument.
Getting a widget for the PDTextField.
Getting a rectangle for the Widget.
Setting the width and the height of the rectangle of the widget.
It would solve it. In my case, I have a height of 20 for a non multiline text and another of 80 for a multiline textfield.You can see them being the last argument of the PDRectangle constructor. The PDRectangle class is used to specify the position and the dimension of the widget that sets it's rectangle to it. The texfield widget will appear as specified by the PDRectangle.
public static PDTextField addTextField(PDDocument pdDoc,PDAcroForm pda,String value,
String default_value,Boolean multiline,float txtfieldsyposition,float pagesheight)
{
int page = (int) (txtfieldsyposition/pagesheight);
if(page+1> pdDoc.getNumberOfPages())
{
ensurePageCapacity(pdDoc,page+1);//add 1 page to doc if needed
}
PDTextField pdtff = new PDTextField(pda);
PDFont font = new PDType1Font(FontName.TIMES_ROMAN);
String appearance = "/TIMES 10 Tf 0 0 0 rg";
try
{
PDFont font_ = new PDType1Font(FontName.HELVETICA);
PDResources resources = new PDResources();
resources.put(COSName.getPDFName("Helv"), font_);
resources.put(COSName.getPDFName("TIMES"), font);
pda.setDefaultResources(resources);
org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget widget = pdtff.getWidgets().get(0);
PDRectangle rect = null;
if(!multiline)
rect = new PDRectangle(80, (pagesheight - (txtfieldsyposition % pagesheight)), 450, 20);
else
rect = new PDRectangle(80,(pagesheight-(txtfieldsyposition%pagesheight)),450,80);
PDPage pd_page = pdDoc.getPage(page);
System.out.println(pd_page.getBBox().getHeight());
widget.setRectangle(rect);
widget.setPage(pd_page);
PDAppearanceCharacteristicsDictionary fieldAppearance = new PDAppearanceCharacteristicsDictionary(new COSDictionary());
fieldAppearance.setBorderColour(new PDColor(new float[]{0,0,0}, PDDeviceRGB.INSTANCE));
fieldAppearance.setBackground(new PDColor(new float[]{255,255,255}, PDDeviceRGB.INSTANCE));
widget.setAppearanceCharacteristics(fieldAppearance);
widget.setPrinted(true);
pd_page.getAnnotations().add(widget);
System.out.println("before appearance " +pdtff.getDefaultAppearance());
pdtff.setDefaultAppearance(appearance);
System.out.println("after appearance "+pdtff.getDefaultAppearance());
if(multiline)
{
pdtff.setMultiline(true);
}
pdtff.setDefaultValue("");
pdtff.setValue(value.replaceAll("\u202F"," "));
pdtff.setPartialName( page +""+(int)txtfieldsyposition);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(IllegalArgumentException e)
{
e.printStackTrace();
}
return pdtff;
}

itext 5.5 Portrait orientation not working from new page

I run the following code for an HTML file with Tables.
I am able to convert HTML to PDF for first page with margins all sides.
But as I do document.newPage(); and apply document.setPageSize(); its not working. Margins are not present.
PDF is borderless, without any margins.
Pls guide.
Code:
public class Potrait_ParseHtmlObjects {
public static final String HTML = "C:/h.html";
public static final String DEST = "C:/test33.pdf";
public void createPdf(String file) {
// Parse HTML into Element list
try{
XMLWorkerHelper helper = XMLWorkerHelper.getInstance();
// CSS
CSSResolver cssResolver = helper.getDefaultCssResolver(true);
CssFile cssFile = helper.getCSS(new FileInputStream("D:\\Itext_Test\\Test\\src\\test.css"));
cssResolver.addCss(cssFile);
// HTML
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
htmlContext.autoBookmark(false);
//mycode starts
FontFactory.registerDirectories();
//mycode ends
// Pipelines
ElementList elements = new ElementList();
ElementHandlerPipeline end = new ElementHandlerPipeline(elements, null);
HtmlPipeline html = new HtmlPipeline(htmlContext, end);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
// XML Worker
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);
//mycode starts
p.parse(new FileInputStream(HTML),Charset.forName("UTF-8"));//changed for Charset Encoding
// step 1
Document document = new Document();
// step 2
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
writer.setInitialLeading(12.5f);
// step 3
document.open();
// step 4
Rectangle left = new Rectangle(33,33,550,770);
document.setPageSize(left);
System.out.println("1"+document.getPageSize());
ColumnText column = new ColumnText(writer.getDirectContent());
column.setSimpleColumn(left);
int runDirection = PdfWriter.RUN_DIRECTION_LTR;
column.setRunDirection(runDirection);
int status = ColumnText.START_COLUMN;
for (Element e : elements) {
if (e instanceof PdfPTable) {
PdfPTable table = (PdfPTable) e;
for (PdfPRow row : table.getRows()) {
for (PdfPCell cell : row.getCells()) {
if(cell!=null)
cell.setRunDirection(runDirection);
}
}
}
if (ColumnText.isAllowedElement(e)) {
column.addElement(e);
status = column.go();
while (ColumnText.hasMoreText(status)) {
Rectangle left1 = new Rectangle(50,50,500,700);
document.newPage();
document.setPageSize(left1);
column.setSimpleColumn(left1);
status = column.go();
}
}
}
// step 5
document.close();
}catch(Exception ex)
{ex.printStackTrace();}
}
/**
* Main method
*/
public static void main(String[] args) throws IOException, DocumentException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new Potrait_ParseHtmlObjects().createPdf(DEST);
}
}
You initialize all page parameters when you do document.newPage(), hence changing the page size or margins doesn't make sense after triggering document.newPage(). If you want a different page size (or orientation, or margins), you need to set the values for the page size, orientation and margins before invoking document.newPage() (and before document.open() if you want to change the first page).
For instance: in your case, you should create your document like this:
Document document = new Document(new Rectangle(33,33,550,770));
And you should change the page size like this:
document.setPageSize(left1);
document.newPage();
column.setSimpleColumn(left1);
You don't have any margins because you use the same Rectangle for the page size as for the column. You are creating a PDF of which the coordinate of the lower-left corner is not equal to (0, 0). This isn't illegale, but it's unusual. My guess is that you want to do something like this:
document.setPageSize(new Rectangle(0, 0, 550, 750););
document.newPage();
column.setSimpleColumn(new Rectangle(50,50,500,700));
This will result in a page size of 7.64 by 10.42 inch (550 by 750 pt) and you'll have a margin of 0
69 inches on every side (50 pt).

Categories

Resources