itext pdf : how to position element above footer - java

I am trying to generate pdf file using itext. I need to add an element(Paragraph) above footer in the last page. I don't know how to position the element in that position.

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.ExceptionConverter;
import com.lowagie.text.Image;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfPageEventHelper;
import com.lowagie.text.pdf.PdfWriter;
public class PdfHeaderDecorator extends PdfPageEventHelper
{
public PdfHeaderDecorator()
{
super();
}
public void onEndPage(PdfWriter writer, Document document)
{
PdfPTable tableF = new PdfPTable(3);
try
{
tableF.setWidths(new int[]
{ 24, 24, 2 });
tableF.setTotalWidth(527);
tableF.setLockedWidth(true);
tableF.getDefaultCell().setFixedHeight(9);
tableF.getDefaultCell().setBorder(Rectangle.BOTTOM);
tableF.addCell(new Phrase("SOME Text"));
tableF.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
tableF.addCell(new Phrase(String.format("page %d ", writer.getPageNumber())));
PdfPCell cell = new PdfPCell(new Phrase("bla bla bla"));
cell.setBorder(Rectangle.BOTTOM);
tableF.addCell(cell);
tableF.writeSelectedRows(0, -1, 34, 30, writer.getDirectContent());
}
catch (DocumentException de)
{
throw new ExceptionConverter(de);
}
}
}
And add your header decorator to page event
pdfWriter.setPageEvent(new PdfHeaderDecorator());

Related

apache-poi excel generation: different image size on multiple sheets

I'm working on piece of code that generates Excel (*.xlsx) workbook with 2 sheets. On both I'm going to place in the top left corner the same logo.png picture (151x90px). First sheet differs only from the second in first column width. It's wider on first sheet.
After excel file generation the picture on the first sheet looks fine however on the second sheet it's wider (110%)
How can I make pictures have it's original size on both sheets?
I'm using apache-poi 3.17
Here is my example code:
package mchodun.excel;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Paths;
public class ExcelFileTest {
#Test
public void testImage() throws IOException {
Workbook workbook = new SXSSFWorkbook(100);
InputStream is = new FileInputStream(
"/Users/mchodun/Desktop/logo.png");
byte[] pictureBytes = IOUtils.toByteArray(is);
createSheet(workbook, pictureBytes, true);
createSheet(workbook, pictureBytes, false);
final File fileDest = Paths.get("/Users/mchodun/Desktop", "test.xlsx")
.toFile();
// gets output stream
final OutputStream out = new FileOutputStream(fileDest);
workbook.write(out);
out.flush();
out.close();
}
private void createSheet(Workbook workbook, byte[] pictureBytes,
boolean changeColumnWidth) {
final int pictureIdx = workbook.addPicture(pictureBytes,
Workbook.PICTURE_TYPE_PNG);
Sheet sheet = workbook.createSheet();
if (changeColumnWidth) {
sheet.setColumnWidth(0, 16000);
}
final CreationHelper helper = workbook.getCreationHelper();
final Drawing drawing = sheet.createDrawingPatriarch();
final ClientAnchor anchor = helper.createClientAnchor();
// create an anchor with upper left cell and bottom right cell
anchor.setCol1(0);
anchor.setRow1(0);
anchor.setCol2(0);
anchor.setRow2(0);
Picture picture = drawing.createPicture(anchor, pictureIdx);
Row row0 = sheet.createRow(0);
row0.setHeight((short) (picture.getImageDimension().getHeight() * 15));
Row row1 = sheet.createRow(1);
Cell cell10 = row1.createCell(0);
cell10.setCellValue("Value");
picture.resize();
}
}

How to dynamically create a footer with Itext in Java?

I have a serious problem with my footer generator. It has the function to describe one specific word from the page (I think that is called a footnote).
This function doesn't quite work yet, anyways. The problem is that my footer can have 1, all the way to 20 or something lines. And in most cases, it is overlapping with the text.
Here is the code of my footer creator:
Font fontTimes = FontFactory.getFont(FontFactory.TIMES_ROMAN, 10,
Font.NORMAL);
PdfPTable table = new PdfPTable(1);
table.getDefaultCell().setBorder(Rectangle.TOP);
table.addCell("all the descriptions.");
table.writeSelectedRows(0, -1, document.left(document.leftMargin()),
table.getTotalHeight() + document.bottom(document.bottomMargin()),
writer.getDirectContent());
The rest of the pages are just created with lists that contains paragraphs, they are just added in the document. And I use "onEndPage" to put the footer in every page.
Here is some of the code I use to create and write in the document:
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(this.fileStorageLocation.resolve(caminhoDoc) + File.separator + nomeDocumento + ".pdf"));
document.setPageSize(PageSize.A4);
document.setMargins(36, 36, 36, 55);
document.setMarginMirroring(false);
writer.setPageEvent(this);
//creating lists...
document.add(mainList);
The pdf is great, except the footer, that is overlapping the rest of the content. I am not sure how to fix it, I'm thinking that maybe the solution is to calculate the space that the footer will need, then set the specific page size to fit with that blank space for the footer.
Here is a small code sample to add footer dynamically to each page of the pdf using the PdfPageEventHelper interface
package com.asu.util;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletContext;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.html.WebColors;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
public class HeaderFooter extends PdfPageEventHelper {
/** Alternating phrase for the header. */
Phrase[] header = new Phrase[2];
/** Current page number (will be reset for every chapter). */
int pagenumber;
private ServletContext context;
private String domainName;
private String createdDate;
public HeaderFooter(ServletContext context, String reportType, String
createdDate, String domainName) {
this.context = context;
this.reportType = reportType;
this.createdDate = createdDate;
this.domainName = domainName;
// TODO Auto-generated constructor stub
}
/**
* Adds the footer.
*
* #see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(com.itextpdf.text.pdf.PdfWriter,
* com.itextpdf.text.Document)
*/
public void onEndPage(PdfWriter writer, Document document) {
Image image;
Font fontStyle = new Font();
fontStyle.setColor(255, 255, 255);
fontStyle.setSize(6);
try {
image = Image.getInstance(context.getRealPath("template//images//footer1.png"));
int indentation = 0;
float scaler = ((document.getPageSize().getWidth() - indentation) / image.getWidth()) * 100;
image.scalePercent(scaler);
image.setAbsolutePosition(0, 0);
document.add(image);
} catch (Exception e) {
e.printStackTrace();
}
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-YYYY");
String date = sdf.format(new Date());
ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER,
new Phrase(String.format("Page - %d, Printed on : %s %s", pagenumber, date,
domainName), fontStyle),
(document.getPageSize().getWidth()) / 2, document.bottomMargin() - 28.5f, 0);
}
}
Then call the headerfooter onEndPage() from the pdf generation method
HeaderFooter headerFooter = new HeaderFooter(context, "reportType",
reportCreatedDate, domainName);

I am using itext to generate pdf. Now , I want to make paragrap align same with table, what should Ido?

Just like the image, I want to make 1 and 3 align same with 2. The table is default alignment.
What should I do?
Here is a simple way of doing it , add both to the same paragraph
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class ItextMain {
public static final String DEST = "simple_table4.pdf";
public static void main(String[] args) throws IOException, DocumentException {
File file = new File(DEST);
// file.getParentFile().mkdirs();
new ItextMain().createPdf(DEST);
}
public void createPdf(String dest) throws IOException, DocumentException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
document.add(new Paragraph("1-Not aligned with table"));
document.add(new Chunk());
Paragraph p = new Paragraph();
p.setIndentationLeft(20);// (20);
PdfPTable table = new PdfPTable(4);
for (int aw = 0; aw < 16; aw++) {
table.addCell("hi");
}
table.setHorizontalAlignment(Element.ALIGN_LEFT);
p.add(table);
//document.add(table);
p.add("3- Aligned with table");
document.add(p);
document.close();
}
}
The iText 5 PdfPTable class has a width percentage attribute which holds the width percentage that the table will occupy in the page. By default this value is 80 and the resulting table is horizontally centered on the page, i.e. in particular it is indented.
To prevent this, simply set the percentage value to 100:
PdfPTable table = ...;
table.setWidthPercentage(100);
Alternatively set the horizontal alignment:
table.setHorizontalAlignment(Element.ALIGN_LEFT);

Getting read values from file and then appending them to textArea

I am currently working on an assignment in which I need to make an application that has two buttons: read/write, and a textArea with a gray background and blue text, that will display the read content of a file that is written to on button press. I have to save an array of 5 numbers, the date, and a double (2.5).
I have gotten to the point of getting everything to work except for the appending of the text to the textArea... no matter where I seem to pass the value it gives me an error or tells me that it doesn't exist as a variable!
My question is: How do I get the values that I have read from the file to update the text in the textArea instead of just console?
Here is my first file which will create the application and populate the scene. The buttons and text area are all the correct color.
package chapter17;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import java.io.IOException;
import javafx.scene.layout.Region;
import javafx.scene.control.TextArea;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
public class Exercise17_5 extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
HBox hBox = new HBox();
hBox.setSpacing(10);
hBox.setAlignment(Pos.CENTER);
Button write = new Button("Write");
Button read = new Button("Read");
TextArea readText = new TextArea("This is text testing...");
readText.setPrefColumnCount(15);
readText.setPrefRowCount(5);
readText.setWrapText(true);
readText.setStyle("-fx-text-fill: blue");
//readText.setStyle("-fx-background-color: grey");
readText.setFont(Font.font("Times", 20));
hBox.getChildren().addAll(write, read, readText);
ReadWrite readWriting = new ReadWrite();
write.setOnAction(e -> {
try {
readWriting.write();
}
catch (IOException excepiton) {
excepiton.printStackTrace();
}});
read.setOnAction(e -> {
try {
readWriting.read();
}
catch (IOException exception){
exception.printStackTrace();
}
});
Scene scene = new Scene(hBox,550,550);
primaryStage.setScene(scene);
primaryStage.setTitle("Exercise 17.5");
primaryStage.show();
Region region = (Region) readText.lookup(".content");
region.setStyle("-fx-background-color: gray");
}
}
Here is the second file that will contain the read and write methods, and the variables that store what is read. I can get them to print out to console as demonstrated below. They need to be appended to my already existing textArea readText.
package chapter17;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;
public class ReadWrite extends Exercise17_5 {
int[] numbers = {1, 2, 3, 4, 5};
public ReadWrite(){
};
public void write() throws IOException {
try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("Exercise17_5.dat"))){
output.writeObject(numbers);
output.writeObject(new Date());
output.writeDouble(2.5);
}
catch (IOException exception) {
exception.printStackTrace();
}
}
public void read() throws IOException {
try{
FileInputStream inputFile = new FileInputStream("Exercise17_5.dat");
ObjectInputStream input = new ObjectInputStream(inputFile);
int[] numbers = (int[])(input.readObject());
java.util.Date date = (java.util.Date)(input.readObject());
double decimal = (double)(input.readDouble());
for (int i = 0; i < numbers.length; i++){
System.out.print(numbers[i] + " ");
}
System.out.println();
System.out.println(decimal);
System.out.println(date);
input.close();
}
catch (IOException | ClassNotFoundException exception2){
exception2.printStackTrace();
}
}
}

Html binary image to pdf in java

I have a html file which has image in binary form.
I want to convert that to pdf using java.
Can anyone please help me with this?
And the Html file contains Base64 image file
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.text.Chunk;
public class Test{
public static void main(String args[]){
try {
Document document = new Document();
// step 2
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("Test.pdf"));
// step 3
document.open();
document.newPage();
document.add(new Chunk(""));
// step 4
XMLWorkerHelper.getInstance().parseXHtml(writer, document,new FileInputStream("/home/farheen/workspace/html.to.pdf/test.html"));
//step 5
document.close();
System.out.println( "PDF Created!" );
}catch (Exception e) {
e.printStackTrace();
}
}
}
You can use itext
With this example code from here
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
public class ImageExample {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("Image.pdf"));
document.open();
Image image1 = Image.getInstance("watermark.png");
document.add(image1);
String imageUrl = "http://jenkov.com/images/" +
"20081123-20081123-3E1W7902-small-portrait.jpg";
Image image2 = Image.getInstance(new URL(imageUrl));
document.add(image2);
document.close();
} catch(Exception e){
e.printStackTrace();
}
}
}

Categories