**Code I am working on to get the text and images getting copied in the PDF but tables are not getting copied from word document
Here i am fetching the text and images first from the word document using apache poi and then i want to write the tables from the word document to pdf document.
Function considering the page size to be A4 as a standard one
Have a look at convertWordToPdf function in the below code .
public static void convertWordToPdf(final String src, final String desc) {
try {
final FileInputStream fs = new FileInputStream(src);
final XWPFDocument doc = new XWPFDocument(fs);
final Document pdfdoc = new Document(PageSize.A4, 72, 72, 72, 72);
final PdfWriter pwriter = PdfWriter.getInstance(pdfdoc,
new FileOutputStream(desc));
pwriter.setInitialLeading(20);
final List<XWPFParagraph> plist = doc.getParagraphs();
pdfdoc.open();
for (int i = 0; i < plist.size(); i++) {
final XWPFParagraph pa = (XWPFParagraph)plist.get(i);
final List<XWPFRun> runs = pa.getRuns();
for (int j = 0; j < runs.size(); j++) {
final XWPFRun run = (XWPFRun) runs.get(j);
final List<XWPFPicture> piclist = run.getEmbeddedPictures();
final Iterator<XWPFPicture> iterator = piclist.iterator();
List<XWPFTable> tabList = doc.getTables();
final Iterator<XWPFTable> tabIterator = tabList.iterator();
while (iterator.hasNext()) {
final XWPFPicture pic = (XWPFPicture) iterator.next();
final XWPFPictureData picdata = pic.getPictureData();
final byte[] bytepic = picdata.getData();
final Image imag = Image.getInstance(bytepic);
imag.scaleAbsoluteHeight(40);
imag.scaleAbsoluteWidth((imag.getWidth() * 30) / imag.getHeight());
pdfdoc.add(imag);
}
final int color = getCode(run.getColor());
Font f = null;
if (run.isBold() && run.isItalic())
f = FontFactory.getFont(FontFactory.TIMES_ROMAN,
run.getFontSize(), Font.BOLDITALIC,
new Color(color));
else if (run.isBold())
f = FontFactory
.getFont(FontFactory.TIMES_ROMAN,
run.getFontSize(), Font.BOLD,
new Color(color));
else if (run.isItalic())
f = FontFactory.getFont(FontFactory.TIMES_ROMAN, run
.getFontSize(), Font.ITALIC, new Color(
color));
else if (run.isStrike())
f = FontFactory.getFont(FontFactory.TIMES_ROMAN,
run.getFontSize(), Font.STRIKETHRU,
new Color(color));
else
f = FontFactory.getFont(FontFactory.TIMES_ROMAN, run
.getFontSize(), Font.NORMAL, new Color(
color));
final String text = run.getText(-1);
byte[] bs;
if (text != null) {
bs = text.getBytes();
final String str = new String(bs, "UTF-8");
final Chunk chObj1 = new Chunk(str, f);
pdfdoc.add(chObj1);
}
}
pdfdoc.add(new Chunk(Chunk.NEWLINE));
}
pdfdoc.close();
} catch (final Exception e) {
e.printStackTrace();
}
Get the tables from the word document and use the Itext API to write them back
List tablesList = doc.getTables();
pdftable = new PdfPTable(3) ; // Table List Move
for (XWPFTable xwpfTable : tablesList) {
pdftable = new PdfPTable(xwpfTable.getRow(0).getTableCells().size()) ;
List row = xwpfTable.getRows();
for (XWPFTableRow xwpfTableRow : row) {
List cell = xwpfTableRow.getTableCells();
for (XWPFTableCell xwpfTableCell : cell) {
if(xwpfTableCell!=null)
{
//table = new Table(cell.size());
pdftable.addCell(xwpfTableCell.getText());
}
}
}
pdfdoc.add(pdftable);
}
How to add an image over a table with Itext?
I'm using the version 5.5.10
implementation 'com.itextpdf:itextg:5.5.10'
Edit: The image can not be inside the row / column, it must be independent to populate any position on the screen
I'm trying to add an image over the columns of a table, but the result is this:
It always lies below the rows of the column.
To add the image I'm doing so:
public void addImg (int dwb, float x, float y, float desc) {
try{
Bitmap bitmap = dwbToBitmap(context, dwb);
ByteArrayOutputStream stream3 = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream3);
Image image = Image.getInstance(stream3.toByteArray());
stream3.close();
image.scaleToFit(sizeImgFit, sizeImgFit);
image.setAbsolutePosition(35.6f + 10f + x, height-y-sizeImg-(height-desc));
document.add(image);
}catch (Exception e){
log("addImg", e);
}
}
I have already tried to change the order, create the first table and then add the images or vise versa, but it does not work.
Does anyone know how to put the images in position Z above all?
I create the table like this:
public void createTable(ArrayList<String> header, ArrayList<String[]> clients){
float height = 569/header.size();
sizeImg = height;
sizeImgFit = sizeImg - 2;
PdfPTable pdfPTable = new PdfPTable(header.size());
pdfPTable.setWidthPercentage(100);
PdfPCell pdfPCell;
int indexC = 0;
while(indexC < header.size()){
pdfPCell = new PdfPCell(new Phrase(header.get(indexC++), fHeaderText));
pdfPCell.setHorizontalAlignment(Element.ALIGN_CENTER);
pdfPCell.setBackgroundColor(BaseColor.GRAY);
pdfPTable.addCell(pdfPCell);
}
int i = 0;
for(String[] row : clients){
int p = 0;
for(String linha : row){
pdfPCell = new PdfPCell(new Phrase(linha, fText));
pdfPCell.setHorizontalAlignment(Element.ALIGN_CENTER);
pdfPCell.setVerticalAlignment(Element.ALIGN_CENTER);
pdfPCell.setFixedHeight(height);
pdfPTable.addCell(pdfPCell);
log("linha - coluna", i + " - " + p);
p++;
}
i++;
}
//paragraph.add(pdfPTable);
try {
document.add(pdfPTable);
}catch (Exception e){
log("paragraph", e);
}
}
These methods mentioned above are in a class:
public class TemplatePDF {
private Context context;
private File pdfFile;
private Document document;
public PdfWriter pdfWriter;
private Paragraph paragraph;
private Rotate event;
private Font fTitle = new Font(Font.FontFamily.TIMES_ROMAN, 20, Font.BOLD);
private Font fSubTitle = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
private Font fHeaderText = new Font(Font.FontFamily.TIMES_ROMAN, 3, Font.NORMAL, BaseColor.WHITE);
private Font fText = new Font(Font.FontFamily.TIMES_ROMAN, 3);
private Font fHText = new Font(Font.FontFamily.TIMES_ROMAN, 8);
private Font fHighText = new Font(Font.FontFamily.TIMES_ROMAN, 15, Font.BOLD, BaseColor.RED);
private float width = PageSize.A4.getWidth();
private float height = PageSize.A4.getHeight();
public float sizeImg;
public float sizeImgFit;
public TemplatePDF(Context context){
this.context = context;
}
public void openDocument(){
createFile();
try{
document = new Document(PageSize.A4);
pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
event = new Rotate();
document.open();
}catch (Exception e){
Log.e("erro", e.toString());
}
}
private void createFile(){
File folder = new File(Environment.getExternalStorageDirectory().toString(), "PDF");
if(!folder.exists()){
folder.mkdirs();
}
pdfFile = new File(folder, key() + ".pdf");
}
public void closeDocument(){
document.close();
}
...
}
To create PDF, I do so:
//Creating the object
TemplatePDF templatePDF = new TemplatePDF(ficha_pre.this);
templatePDF.openDocument();
templatePDF.addMetaData("Relatório", "Situs", "Woton Sampaio");
templatePDF.addTitles("Relatório", "","Data: " + getDate());
//Creating the table
ArrayList<String> header = new ArrayList<>();
for(int i = 0; i < 55; i++){
header.add(forString(i));
}
ArrayList<pdfItens> itens = arrayItens();
ArrayList<String[]> files = array();
templatePDF.createHeaderFicha(itens);
templatePDF.createTable(header, files);
//Adding image
templatePDF.addImg(R.drawable.ic_a, 0, 20, 566);
The cause for this is that an Image added to the Document is added in a virtual layer underneath that of regular text and tables. Apparently iText developers assumed that text and table elements by default are to be drawn in front of images.
But you can explicitly add the Image to a different virtual layer which is in turn above that of text and tables, in addImg you merely have to replace
document.add(image);
by
pdfWriter.getDirectContent().addImage(image);
Your image in addImg has its AbsolutePosition set. This actually is necessary for images you want to add to the DirectContent because the DirectContent has no idea about current insertion positions or page dimensions.
As an aside, there also is a DirectContentUnder for stuff that shall go even below the layer of Images added via the Document.
I have two chunks, added in phrases and then in paragraph.
Chunk reportTitle= new Chunk("Candidate Login Report ",catFont);
Chunk divisiontitle = new Chunk("Division : \t\t"+divisionName);
Phrase phrase = new Phrase();
phrase.add(reportTitle);
phrase.add(divisiontitle);
Paragraph para = new Paragraph();
para.add(phrase);
I have to set chunk divisiontitle to right aligned. Is there any provision to do this in iIext?
You really answered yourself in your comment.
Chunk reportTitle= new Chunk("Candidate Login Report ",catFont);
Chunk divisiontitle = new Chunk("Division : \t\t"+divisionName);
Phrase phrase = new Phrase();
phrase.add(reportTitle);
phrase.add(divisiontitle);
Paragraph para = new Paragraph();
para.add(phrase);
para.setAlignment(Element.ALIGN_RIGHT);
Then you can add it to any cell and it will be correctly aligned.
bajrangi,
You might want to use ColumnText.showTextAligned() to align your text. Try the following:
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
PdfContentByte canvas = writer.getDirectContent();
ColumnText.showTextAligned(canvas, Element.ALIGN_RIGHT, phrase, xPosition, yPosition, 0);
Cheers!
-Eric
add multiple Chunk and Phrase in itextpdf
package com.pdf.hl;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
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.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class GraphicsStateOperators {
public static final String RESULT = "d:/graphics_state.pdf";
static Font.FontFamily ff = Font.FontFamily.HELVETICA;
static float size = 10;
static float size1 = 8;
public void createPdf(String filename) throws Exception {
Font bold = new Font(Font.FontFamily.HELVETICA, 8f, Font.BOLD);
Font normal = new Font(Font.FontFamily.HELVETICA, 8f, Font.NORMAL);
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(filename));
document.open();
// /////////////////////////////////////////////
PdfPTable tabletmp = new PdfPTable(1);
tabletmp.getDefaultCell().setBorder(Rectangle.NO_BORDER);
tabletmp.setWidthPercentage(100);
PdfPTable table = new PdfPTable(2);
float[] colWidths = { 45, 55 };
table.setWidths(colWidths);
String imageUrl = "http://logo.com/content1/images/logo_heartSmart.jpg";
Image image2 = Image.getInstance(new URL(imageUrl));
image2.setWidthPercentage(60);
table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP);
PdfPCell cell = new PdfPCell();
cell.setBorder(Rectangle.NO_BORDER);
cell.addElement(image2);
table.addCell(cell);
String receiptNo = "123455555555555555";
String collectionDate = "09/09/09";
Chunk chunk1 = new Chunk("Date: ", normal);
Phrase ph1 = new Phrase(chunk1);
Chunk chunk2 = new Chunk(collectionDate, bold);
Phrase ph2 = new Phrase(chunk2);
Chunk chunk3 = new Chunk("\nReceipt No: ", normal);
Phrase ph3 = new Phrase(chunk3);
Chunk chunk4 = new Chunk(receiptNo, bold);
Phrase ph4 = new Phrase(chunk4);
Paragraph ph = new Paragraph();
ph.add(ph1);
ph.add(ph2);
ph.add(ph3);
ph.add(ph4);
table.addCell(ph);
tabletmp.addCell(table);
PdfContentByte canvas = writer.getDirectContent();
canvas.saveState();
canvas.setLineWidth((float) 10 / 10);
canvas.moveTo(40, 806 - (5 * 10));
canvas.lineTo(555, 806 - (5 * 10));
canvas.stroke();
document.add(tabletmp);
canvas.restoreState();
PdfPTable tabletmp1 = new PdfPTable(1);
tabletmp1.getDefaultCell().setBorder(Rectangle.NO_BORDER);
tabletmp1.setWidthPercentage(100);
PdfPTable table1 = new PdfPTable(2);
table1.getDefaultCell().setBorder(Rectangle.NO_BORDER);
table1.getDefaultCell().setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
table1.getDefaultCell().setVerticalAlignment(Element.ALIGN_JUSTIFIED);
float[] colWidths1 = { 60, 40 };
table1.setWidths(colWidths1);
String Patient = "abcddd";
String Email = "test#test.com";
String Phone = "89890099890890";
PdfPCell cell3 = new PdfPCell();
cell3.setBorder(Rectangle.NO_BORDER);
Chunk chunkPatientLabal = new Chunk("Patient: ", normal);
Phrase phPatientLabal = new Phrase(chunkPatientLabal);
Chunk chunkPatient = new Chunk(Patient, bold);
Phrase phPatient = new Phrase(chunkPatient);
Chunk chunkEmailLabal = new Chunk("\nEmail: ", normal);
Phrase phEmailLabal = new Phrase(chunkEmailLabal);
Chunk chunkEmail = new Chunk(Email, bold);
Phrase phEmail = new Phrase(chunkEmail);
Chunk chunkPhoneLabal = new Chunk("\nPhone: ", normal);
Phrase phPhoneLabal = new Phrase(chunkPhoneLabal);
Chunk chunkPhone = new Chunk(Phone, bold);
Phrase phPhone = new Phrase(chunkPhone);
Paragraph phN = new Paragraph();
phN.add(phPatientLabal);
phN.add(phPatient);
phN.add(phEmailLabal);
phN.add(phEmail);
phN.add(phPhoneLabal);
phN.add(phPhone);
cell3.addElement(phN);
table1.addCell(cell3);
PdfPCell cell4 = new PdfPCell();
cell4.getBorderWidthRight();
cell4.setBorder(Rectangle.NO_BORDER);
String ReferingPhysician = "phy Patient";
Chunk chunkRefPhyLabal = new Chunk("Refering Physician: ", normal);
Phrase phRefPhyLabal = new Phrase(chunkRefPhyLabal);
Chunk chunkRefPhy = new Chunk(ReferingPhysician, bold);
Phrase phRefPhy = new Phrase(chunkRefPhy);
Paragraph phN1 = new Paragraph();
phN1.add(phRefPhyLabal);
phN1.setAlignment(com.itextpdf.text.Element.ALIGN_RIGHT);
phN1.add(phRefPhy);
cell4.addElement(phN1);
table1.addCell(cell4);
tabletmp1.addCell(table1);
tabletmp1.setSpacingAfter(10);
document.add(tabletmp1);
PdfPTable table7 = new PdfPTable(1);
table7.setWidthPercentage(100);
PdfPCell c7 = new PdfPCell(new Phrase("Payment Summry", new Font(ff,
size, Font.BOLD)));
BaseColor headingColor7 = WebColors.getRGBColor("#989898");
c7.setBackgroundColor(headingColor7);
c7.setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_LEFT);
table7.addCell(c7);
table7.setSpacingAfter(2f);
document.add(table7);
// ////////////////////////////////////////////////////////
PdfPTable tabletmp2 = new PdfPTable(1);
BaseColor headingColor8 = WebColors.getRGBColor("#F0F0F0");
tabletmp2.setWidthPercentage(100);
PdfPTable table8 = new PdfPTable(2);
table8.getDefaultCell().setBorder(Rectangle.NO_BORDER);
table8.getDefaultCell().setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
table8.getDefaultCell().setVerticalAlignment(Element.ALIGN_JUSTIFIED);
float[] colWidths8 = { 50, 50 };
table8.setWidths(colWidths8);
PdfPCell cellPaymentSummry = new PdfPCell();
cellPaymentSummry.setBackgroundColor(headingColor8);
cellPaymentSummry.setBorder(Rectangle.NO_BORDER);
Chunk chunkPaymentInvoiceLabal = new Chunk("Invoice Id", normal);
Phrase phPaymentInvoiceLabal = new Phrase(chunkPaymentInvoiceLabal);
Chunk chunkPaymentModeLabal = new Chunk("\nPayment Mode", normal);
Phrase phPaymentModeLabal = new Phrase(chunkPaymentModeLabal);
Chunk chunkAmountReceivedLabal = new Chunk("\nAmount Received", normal);
Chunk chunkAmountDueLabal = new Chunk("\nAmount Due", normal);
Phrase phAmountDueLabal = new Phrase(chunkAmountDueLabal);
Phrase phAmountReceivedLabal = new Phrase(chunkAmountReceivedLabal);
Paragraph phPaymentSummry = new Paragraph();
phPaymentSummry.add(phPaymentInvoiceLabal);
phPaymentSummry.add(phPaymentModeLabal);
phPaymentSummry.add(phAmountReceivedLabal);
phPaymentSummry.add(phAmountDueLabal);
cellPaymentSummry.addElement(phPaymentSummry);
table8.addCell(cellPaymentSummry);
PdfPCell cellPaymentSummry1 = new PdfPCell();
cellPaymentSummry1.setBackgroundColor(headingColor8);
cellPaymentSummry1.getBorderWidthRight();
cellPaymentSummry1.setBorder(Rectangle.NO_BORDER);
String PaymentMode = "rannnnnnnnnnnnnnnnn";
String amountReceived = "2.33";
String amountDue = "28.00";
String invoice = "123";
Chunk chunkPaymentInvoicel = new Chunk(invoice, bold);
Phrase phPaymentInvoice = new Phrase(chunkPaymentInvoicel);
Chunk chunkPaymentMode = new Chunk("\n" + PaymentMode, bold);
Phrase phPaymentMode = new Phrase(chunkPaymentMode);
Chunk chunkAmountReceived = new Chunk("\n$" + amountReceived, bold);
Phrase phAmountReceived = new Phrase(chunkAmountReceived);
Chunk chunkAmountDue = new Chunk("\n$" + amountDue, bold);
Phrase phAmountDue = new Phrase(chunkAmountDue);
Paragraph phPaymentSummry1 = new Paragraph();
phPaymentSummry1.add(phPaymentInvoice);
phPaymentSummry1.add(phPaymentMode);
phPaymentSummry1.setAlignment(com.itextpdf.text.Element.ALIGN_RIGHT);
phPaymentSummry1.add(phAmountReceived);
phPaymentSummry1.add(phAmountDue);
cellPaymentSummry1.addElement(phPaymentSummry1);
table8.addCell(cellPaymentSummry1);
tabletmp2.addCell(table8);
document.add(tabletmp2);
document.close();
}
/**
* Main method.
*
* #param args
* no arguments needed
* #throws DocumentException
* #throws IOException
*/
public static void main(String[] args) throws Exception {
new GraphicsStateOperators().createPdf(RESULT);
System.out.println("Done Please check........");
}
}
via https://stackoverflow.com/a/47644620:
Chunk glue = new Chunk(new VerticalPositionMark())
Paragraph p = new Paragraph();
p.Add("Text to the left");
p.Add(glue);
p.Add("Text to the right");
tested as working under iTextSharp.LGPLv2.Core 1.4.5 (iText 4)
#WebServlet(name = "Servlet")
public class PDFServlet extends HttpServlet {
private String RESOURCE = "images/logo-new.png";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
response.setContentType("application/pdf");
Document document = new Document(PageSize.LETTER);
PdfWriter writer = null;
try {
writer = PdfWriter.getInstance(document, response.getOutputStream());
document.open();
document.add(createHeaderTable());
document.add(comapnyNameTable());
document.add(createAddressTable());
document.add(getTable());
document.add(createFooterTable());
PdfContentByte canvas = writer.getDirectContent();
canvas.setLineWidth((float) 10 / 10);
canvas.moveTo(40, 765 - (5 * 10));
canvas.lineTo(570, 770 - (5 * 10));
canvas.stroke();
document.close();
} catch (DocumentException e) {
e.printStackTrace();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
private PdfPTable createHeaderTable(){
Font bold = new Font(Font.FontFamily.HELVETICA, 8f, Font.BOLD);
Font normal = new Font(Font.FontFamily.HELVETICA, 8f, Font.NORMAL);
PdfPTable table = new PdfPTable(2);
try{
table.setWidthPercentage(100f);
table.setHorizontalAlignment(0);;
table.setSpacingBefore(10);
table.setWidths(new int[]{2, 6});
Image img = Image.getInstance(RESOURCE);
img.scalePercent(28f);
PdfPCell pdfPCell = new PdfPCell(img,true);
//pdfPCell.addElement(img);
pdfPCell.setBorder(Rectangle.NO_BORDER);
pdfPCell.setFixedHeight(50);
table.addCell(pdfPCell);
Paragraph paragraph = new Paragraph(10);
paragraph.add(new Chunk("Date:",bold));
paragraph.add(new Chunk("11-09-2015",normal));
paragraph.add(new Chunk("\nOrder Id:",bold));
paragraph.add(new Chunk("OrderId#12345",normal));
paragraph.setIndentationLeft(260);
table.addCell(newPdfPcel(paragraph,50));
}
catch (DocumentException e){
e.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
return table;
}
private PdfPTable createAddressTable(){
PdfPTable table = new PdfPTable(2);
Font bold = new Font(Font.FontFamily.HELVETICA, 8f, Font.BOLD);
Font normal = new Font(Font.FontFamily.HELVETICA, 8f, Font.NORMAL);
try{
table.setWidthPercentage(100f);
table.setHorizontalAlignment(0);;
table.setSpacingBefore(10);
table.setSpacingAfter(10);
table.setWidths(new int[]{2, 6});
Paragraph paragraph = new Paragraph(10);
paragraph.add(new Chunk("Billed To",bold));
paragraph.add(new Chunk("\nOrdered By tdhdghfjghjg fvgfdghgfhg gfhggjdjh ghgfhgjhgjhg gfhghjghj dghgfh ghggfhgfh ghgffgh ghjggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg", normal));
paragraph.setIndentationRight(40);
table.addCell(newPdfPcel(paragraph,60));
Paragraph paragraph2 = new Paragraph(10);
paragraph2.add(new Chunk("Service By ",bold));
paragraph2.add(new Chunk("\nService B gfdsgfdhghhhhy tdhdghfjghjg fvgfdghgfhg gfhggjdjh ghgfhgjhgjhg gfhghjghj dghgfhh ghfddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd",normal));
paragraph2.setIndentationLeft(260);
table.addCell(newPdfPcel(paragraph2,60));
Paragraph paragraph3 = new Paragraph(10);
paragraph3.add(new Chunk("Payment Method:", bold));
paragraph3.add(new Chunk("\nVisa ending with *888888888888888888888888888888888888888888888**********123,\nseeenu#gmail.com",normal));
table.addCell(newPdfPcel(paragraph3,60));
Paragraph paragraph4 = new Paragraph(10);
paragraph4.add(new Chunk("Order Date:",bold));
paragraph4.add(new Chunk("\nMarch 7,2014",normal));
paragraph4.setIndentationLeft(260);
table.addCell(newPdfPcel(paragraph4,60));
}
catch (DocumentException e){
e.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
return table;
}
private PdfPTable comapnyNameTable(){
PdfPTable table = new PdfPTable(1);
Font bold = new Font(Font.FontFamily.HELVETICA, 8f, Font.BOLD);
Font normal = new Font(Font.FontFamily.HELVETICA, 8f, Font.NORMAL);
try{
table.setWidthPercentage(100f);
Paragraph paragraph = new Paragraph(10);
paragraph.add(new Chunk("Travels Company",bold));
paragraph.add(new Chunk("\nOrdered By tdhdghfjghjg fvgfdghgfhg gfhggjdjh ghgfhgjhgjhg gfhghjghj dghgfh ghggfhgfh ghgffgh ghjggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg",normal));
paragraph.setIndentationLeft(200f);
paragraph.setIndentationRight(200f);
table.addCell(newPdfPcel(paragraph,60));
}
catch (Exception e){
e.printStackTrace();
}
return table;
}
private PdfPTable createFooterTable(){
PdfPTable table = new PdfPTable(2);
Font bold = new Font(Font.FontFamily.HELVETICA, 8f, Font.BOLD);
Font normal = new Font(Font.FontFamily.HELVETICA, 8f, Font.NORMAL);
try{
table.setWidthPercentage(100f);
table.setHorizontalAlignment(0);;
table.setSpacingBefore(10);
table.setSpacingAfter(10);
table.setWidths(new int[]{2, 6});
Paragraph paragraph = new Paragraph(10);
paragraph.add(new Chunk("Tearms & Conditions",bold));
paragraph.add(new Chunk("\ngfdhgfhgfh",normal));
Paragraph paragraph2 = new Paragraph(10);
paragraph2.add(new Chunk("Aggrigate Service By",bold));
paragraph2.add(new Chunk("\nTruckWay",normal));
paragraph2.setIndentationLeft(260);
table.addCell(newPdfPcel(paragraph2,0));
}
catch (DocumentException e){
e.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
return table;
}
private Paragraph createParagraph(String text,Font font,float indentationLeft,float indentationRight){
Paragraph paragraph = new Paragraph(10);
paragraph.add(new Chunk(text,font));
paragraph.setIndentationLeft(indentationLeft);
paragraph.setIndentationRight(indentationRight);
return paragraph;
}
private PdfPCell newPdfPcel(Paragraph paragraph,float fixedHight){
PdfPCell pdfPCell = new PdfPCell();
pdfPCell.addElement(paragraph);
pdfPCell.setBorder(Rectangle.NO_BORDER);
pdfPCell.setFixedHeight(fixedHight);
return pdfPCell;
}
public PdfPTable getTable()throws DocumentException, IOException {
// Create a table with 7 columns
PdfPTable table = new PdfPTable(2);
table.setWidthPercentage(100f);
// Add the first header row
PdfPCell cell = new PdfPCell(new Phrase("Order Details", FontFactory.getFont("Arial",10,Font.BOLD,BaseColor.BLACK)));
cell.setBackgroundColor(BaseColor.CYAN);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setColspan(7);
table.addCell(cell);
Font font = new Font();
font.setSize(10);
font.setFamily("Arial");
table.addCell(createCel("From Place",font,Element.ALIGN_LEFT));
table.addCell(createCel("Hyderabad",font,Element.ALIGN_LEFT));
table.addCell(createCel("To Place",font,Element.ALIGN_LEFT));
table.addCell(createCel("Bangolore",font,Element.ALIGN_LEFT));
table.addCell(createCel("Truck RequestDate",font,Element.ALIGN_LEFT));
table.addCell(createCel("09/9/15",font,Element.ALIGN_LEFT));
table.addCell(createCel("Truck Type",font,Element.ALIGN_LEFT));
table.addCell(createCel("6 wheeler",font,Element.ALIGN_LEFT));
table.addCell(createCel("No OfTrucks",font,Element.ALIGN_LEFT));
table.addCell(createCel("1",font,Element.ALIGN_LEFT));
table.addCell(createCel("Total Capacity",font,Element.ALIGN_LEFT));
table.addCell(createCel("8",font,Element.ALIGN_LEFT));
table.addCell(createCel("Total Amount",font,Element.ALIGN_LEFT));
table.addCell(createCel("1000.00",font,Element.ALIGN_LEFT));
table.addCell(createCel("From Addressy",font,Element.ALIGN_LEFT));
table.addCell(createCel("hyd",font,Element.ALIGN_LEFT));
table.addCell(createCel("To Address",font,Element.ALIGN_LEFT));
table.addCell(createCel("Bang",font,Element.ALIGN_LEFT));
table.addCell(createCel("Advance",font,Element.ALIGN_RIGHT));
table.addCell(createCel("1000.00",font,Element.ALIGN_RIGHT));
table.addCell(createCel("Service Charges",font,Element.ALIGN_RIGHT));
table.addCell(createCel("25.00",font,Element.ALIGN_RIGHT));
table.addCell(createCel("Total",font,Element.ALIGN_RIGHT));
table.addCell(createCel("1000.25",font,Element.ALIGN_RIGHT));
return table;
}
private PdfPCell createCel(String text,Font font,int alignment){
PdfPCell pdfPCel = new PdfPCell(new Phrase(text,font));
pdfPCel.setHorizontalAlignment(alignment);
return pdfPCel;
}
}
i am having a resultset and i have to write all the data available in resultset to a text file and populate the same to user for downloading.
i have done the below code to export to excel using poi, same way how to do for text file.
if(exportTo.equals("excel"))
{
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment; filename=\"" + reportName + ".xls\"");
try {
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet(reportName);
HSSFRow row = null;
HSSFHeader header = sheet.getHeader();
header.setCenter("POC");
header.setLeft("POC");
header.setRight(HSSFHeader.font("Stencil-Normal", "Italic") +
HSSFHeader.fontSize((short) 16) + reportName);
//to add water mark
/*HSSFPatriarch dp = sheet.createDrawingPatriarch();
HSSFClientAnchor anchor = new HSSFClientAnchor
(0, 0, 1023, 255, (short) 2, 4, (short) 13, 26);
HSSFTextbox txtbox = dp.createTextbox(anchor);
HSSFRichTextString rtxt = new HSSFRichTextString("POC");
HSSFFont draftFont = hwb.createFont();
draftFont.setColor((short) 27);
draftFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
draftFont.setFontHeightInPoints((short) 192);
draftFont.setFontName("Verdana");
rtxt.applyFont(draftFont);
txtbox.setString(rtxt);
txtbox.setLineStyle(HSSFShape.LINESTYLE_NONE);
txtbox.setNoFill(true);*/
HSSFCellStyle style = hwb.createCellStyle();
style.setBorderTop((short) 6); // double lines border
style.setBorderBottom((short) 1); // single line border
style.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);
HSSFFont font = hwb.createFont();
font.setBoldweight((short) 700);
// Create Styles for sheet.
HSSFCellStyle headerStyle = hwb.createCellStyle();
headerStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
headerStyle.setFont(font);
headerStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
headerStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
headerStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
headerStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
headerStyle.setAlignment((short) 2);
// create Title for the sheet
HSSFCellStyle titleStyle = hwb.createCellStyle();
HSSFFont titleFont = hwb.createFont();
titleFont.setFontName(HSSFFont.FONT_ARIAL);
titleFont.setFontHeightInPoints((short) 15);
titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
titleFont.setColor(HSSFColor.BLUE.index);
titleStyle.setFont(titleFont);
titleStyle.setAlignment((short)2);
row = sheet.createRow((short)1);
HSSFCell secondCell = row.createCell((short) 0);
secondCell.setCellValue(new HSSFRichTextString(reportName).toString());
secondCell.setCellStyle(titleStyle);
sheet.addMergedRegion(new Region(1, (short)0, 1, (short)headerCount));
int sno=0;
HSSFRow rowhead = sheet.createRow((short)4);
for (Iterator it = headerMap.keySet().iterator(); it.hasNext();) {
String headerName = (String) headerMap.get(it.next());
HSSFCell headerCell = rowhead.createCell((short)sno);
headerCell.setCellStyle(headerStyle);
headerCell.setCellValue(headerName);
sno++;
}
HSSFCellStyle rowStyle=hwb.createCellStyle();
rowStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
rowStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
rowStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
rowStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
rowStyle.setAlignment((short) 2);
row = custDAO.creadExcelTable(query, sheet, row,rowStyle);
hwb.write(response.getOutputStream());
response.flushBuffer();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public HSSFRow creadExcelTable(String query,HSSFSheet sheet,HSSFRow row,HSSFCellStyle rowStyle ){
int numberOfColumns=0,sno=0,index=5,iterator=1;
Connection connection = getConnection();
if (connection != null) {
try {
PreparedStatement reportTablePS = connection.prepareStatement(query);
ResultSet reportTable_rst = reportTablePS.executeQuery();
ResultSetMetaData reportTable_rsmd = reportTable_rst.getMetaData();
numberOfColumns = reportTable_rsmd.getColumnCount();
int i =0;
while (reportTable_rst.next()) {
row = sheet.createRow((short)index);
sheet.setColumnWidth((short)index, (short)100);
/* if(i == 0){
i = 1;
rowStyle.setFillForegroundColor(HSSFColor.BLUE_GREY.index);
rowStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
System.out.println("BLUE_GREY");
}
else {
i = 0;
System.out.println("LEMON");
rowStyle.setFillForegroundColor(HSSFColor.LEMON_CHIFFON.index);
rowStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
}*/
HSSFCell serialCell = row.createCell((short)sno);
serialCell.setCellStyle(rowStyle);
serialCell.setCellValue(iterator);
for (int columnIterator = 1; columnIterator <= numberOfColumns; columnIterator++) {
String column = reportTable_rst.getString(columnIterator);
sheet.setColumnWidth((short)columnIterator, (short)3000);
HSSFCell rowCell = row.createCell((short)columnIterator);
rowCell.setCellStyle(rowStyle);
rowCell.setCellValue(column);
}
index++;
iterator++;
}
} catch (Exception ex) {
ex.printStackTrace();
}finally {
try {
closeConnection(connection, null, null);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return row;
}
now i have done updto this and really don't know how to go about
if(exportTo.equals("text")){
response.setContentType("text/plain");
response.setHeader("Content-disposition", "attachment; filename=\"" + reportName + ".txt\"");
try {
} catch (Exception e) {
// TODO: handle exception
}
}
this one for creating file in a specified location
Writer writer = null;
try {
String text = "This is a text file";
File file = new File("write.txt");
writer = new BufferedWriter(new FileWriter(file));
writer.write(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
but i want to export the file with dialog, Please help me how to go about.
Regards
I suppose you don't get a dialog box, because your browser can handle text files by itself.
The browser reads the MIME type of the http response (which has been set with response.setContentType("text/plain");)
Most browsers open html, images and text themselves and redirect other file types like audio, pdf's or Office documents to other applications.
So you may need to adjust your browser settings.
I am generating pdf file using com.itextpdf.text.* following is my code which creates the pdf file with title and header higlighted and rows, what i wanted to do is, create a pdf file with image on the top and rows with alternate color, how to do this in using com.itextpdf.text.*
response.setHeader("Content-disposition", "attachment; filename=\"" + reportName + ".pdf\"");
response.setContentType("application/pdf");
PdfWriter.getInstance(document,response.getOutputStream());
try {
document.open();
addTitlePage(document, reportName);
//float[] colsWidth = {1.5f,3f,4f,4f,2f};
List<Float> colsWidth = new ArrayList<Float>();
int iterator = 1;
while (iterator <= headerMap.size()) {
if(iterator==1){
colsWidth.add(1.5f);
}else{
colsWidth.add(3f);
}
iterator++;
}
float[] floatArray = ArrayUtils.toPrimitive(colsWidth.toArray(new Float[0]), 0.0F);
PdfPTable table = new PdfPTable(floatArray);
table.setWidthPercentage(98);
table.setHorizontalAlignment(Element.ALIGN_CENTER);
PdfPCell c1 = new PdfPCell();
for (Iterator it = headerMap.keySet().iterator(); it.hasNext();) {
String headerName = (String) headerMap.get(it.next());
c1 = new PdfPCell(new Phrase(headerName, headerFont));
c1.setBackgroundColor(BaseColor.LIGHT_GRAY);
table.addCell(c1);
}
table.setHeaderRows(1);
table = custDAO.creadPDFTable(query, table);
document.add(table);
document.addAuthor(userViewModel.getUsername());
document.addCreationDate();
document.addCreator("POC");
document.close();
response.flushBuffer();
public PdfPTable creadPDFTable(String query,PdfPTable table){
int numberOfColumns=0,sno=1;
Connection connection = getConnection();
if (connection != null) {
try {
PreparedStatement reportTablePS = connection.prepareStatement(query);
ResultSet reportTable_rst = reportTablePS.executeQuery();
ResultSetMetaData reportTable_rsmd = reportTable_rst.getMetaData();
numberOfColumns = reportTable_rsmd.getColumnCount();
while (reportTable_rst.next()) {
table.addCell(new PdfPCell(new Paragraph(String.valueOf(sno), textFont)));
for (int columnIterator = 1; columnIterator <= numberOfColumns; columnIterator++) {
String column = reportTable_rst.getString(columnIterator);
table.addCell(new PdfPCell(new Paragraph(column, textFont)));
}
sno++;
}
} catch (Exception ex) {
ex.printStackTrace();
}finally {
try {
closeConnection(connection, null, null);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return table;
}
private static void addTitlePage(Document document, String reportName) throws DocumentException {
Paragraph preface = new Paragraph();
addEmptyLine(preface, 1);
/**
* Lets write a big header
*/
Paragraph paragraph = new Paragraph(reportName, titleFont);
paragraph.setAlignment(Element.ALIGN_CENTER);
document.add(paragraph);
/**
* Add one empty line
*/
addEmptyLine(preface, 1);
document.add(preface);
}
private static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}
when i use the following i get the following exception 'getoutputstream() has already called for this response'
i wanted to use this for inserting image.
Image image = Image.getInstance(path+"images/abi.png");
image.setAbsolutePosition(40f, 770f);
image.scaleAbsolute(70f, 50f);
document.add(image);
so how to go about doing this?
UPDATE :
i want to create a pdf file like this i just want to add image on the top and rows with alternate color like this.
http://what-when-how.com/itext-5/decorating-tables-using-table-and-cell-events-itext-5/
(source: what-when-how.com)
(source: what-when-how.com)
You can use XSLFO and Apache FOP. It worked for me. For adding a image I done changes in XSL.
For reference visit
http://www.codeproject.com/Articles/37663/PDF-Generation-using-XSLFO-and-FOP