I am using the Hindi language for displaying header content of table in pdf but it displaying empty cell in header part of table.
I have created like as follows:
HttpServletResponse response = ServletActionContext.getResponse();
Document document = new Document();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, buffer);
writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));
document.open();
PdfPTable lineItemTable = new PdfPTable(cellval);
lineItemTable.setHeaderRows(1);
PdfPCell num1 = new PdfPCell(new Phrase("No",Bold_NORMAL));
num1.setHorizontalAlignment(Element.ALIGN_CENTER);
num1.setBackgroundColor(BaseColor.LIGHT_GRAY);
lineItemTable.addCell(num1);
PdfPCell lineval = new PdfPCell(new Phrase(""));
lineval = new PdfPCell(new Phrase(HindiItenName,Bold_NORMAL));
lineval.setHorizontalAlignment(Element.ALIGN_CENTER);
lineval.setBackgroundColor(BaseColor.LIGHT_GRAY);
lineItemTable.addCell(lineval);
document.add(lineItemTable);
document.close();
response.setContentType("application/pdf;charset=ISO-8859-1");
response.setHeader("Content-Disposition","attachment;filename=Invoice-"+invNumber+".pdf");
response.getOutputStream().write(buffer.toByteArray());
This is my sample code. Can you please help to me. Thanks in advance.
Call
writer.close();
document.close();
response.setContentType("application/pdf");
Closing the writer rounds of some structures in the document. But I have seen many examples where this is not done. So I am not sure.
The content type is for binary and does not need an encoding.
On the error: pick a Unicode font, IDENTITY_H:
final String FONT = "c:/windows/... .ttf";
BaseFont bf = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
document.add(new Paragraph("Font: " + bf.getPostscriptFontName()
+ " with encoding: " + bf.getEncoding()));
Here an embedded font, so there will no problem at the recipient's side.
This is from itextpdf.com, a book excerpt.
For a better browser experience:
byte[] bytes = buffer.toByteArray();
response.setContentLength(bytes.length);
response.getOutputStream().write(bytes);
Related
Hi I am trying to create an PDF using itextpdf.
It is working fine when tested locally.
But after aws deployment I am getting 406 Not Acceptable with java.io.IOException: The document has no pages excpetion.
Many answers are there but those are not related to deployment issues.
Do I need to check any network configuration or problem lies in the pdf generation code?
Following is my code implementation:
Please suggest some solution.
public byte[] createPdf(List<Participant> participantList) throws IOException,
DocumentException, com.google.zxing.WriterException {
Document document = new Document();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
PdfWriter.getInstance(document, byteArrayOutputStream);
document.open();
document.add(createMainTable(participantList));
document.close();
return byteArrayOutputStream.toByteArray();
}
public static PdfPTable createMainTable(List<Participant> optionalParticipant) throws BadElementException,
IOException, com.google.zxing.WriterException {
PdfPTable table = new PdfPTable(2);
logger.info("Main Table was created");
for (int i = 0; i < optionalParticipant.size(); i++) {
PdfPCell cell1 = new PdfPCell();
cell1.setBorderWidth(0);
cell1.setPadding(10f);
cell1.addElement(createSubTable(optionalParticipant.get(i)));
table.addCell(cell1);
}
return table;
}
public static PdfPTable createSubTable(Participant participant) throws BadElementException,
IOException, com.google.zxing.WriterException {
BaseColor baseColor = new BaseColor(150, 150, 150);
PdfPTable table = new PdfPTable(2);
table.setWidthPercentage(100);
PdfPCell cell, cell1, cell2;
Font font = new Font();
font.setSize(10f);
font.setColor(BaseColor.WHITE);
String participantName = participant.getFirstName() + " " + participant.getLastName();
Chunk chunk = new Chunk(participantName, font);
Paragraph head = new Paragraph(" "+chunk);
head.setFont(font);
cell = new PdfPCell(head);
cell.setColspan(2);
cell.setBackgroundColor(baseColor);
cell.setPadding(2f);
table.addCell(cell);
String qrData = participant.getQrCodeData();
Image img = getQRCodeImage(qrData);
font = new Font();
font.setSize(5f);
chunk = new Chunk("\n" + "Event ID: " + participant.getEvent().getEventId() +
"\n\n" + "Unique ID: " + participant.getUniqueId() +
"\n\n" + "Email ID: " + participant.getEmail(), font);
Paragraph body = new Paragraph(chunk);
cell1 = new PdfPCell(body);
cell1.setBorderWidthRight(0);
cell1.setPadding(10f);
cell2 = new PdfPCell();
cell2.addElement(img);
cell2.setBorderWidthLeft(1);
cell2.setPadding(10f);
table.addCell(cell1);
table.addCell(cell2);
logger.info("Sub Table was created");
return table;
}
Please check participantList is not null and contains elements. You can use logger to print size of list before start using it.
logger.info("No of participants: "+participantList.size());
Also, Immediately after opening document, always add an empty chunk to document so that you can avoid this exception.
document.open();
document.add(new Chunk(""));
I am trying to convert some html content to a pdf using the itext PdfWriter, like this:
Document document = new Document();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
InputStream stream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
XMLWorkerHelper.getInstance().parseXHtml(writer, document, stream, Charset.forName("UTF-8"));
document.close();
but the ă ș ț charaters are missing from the generated pdf. I have tried setting the encoding or the font, but with no luck. What I tried was to use a font provider and set it as a param to the parseXHtml method.
I set the encoding, but nothing changed.
XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider();
fontProvider.setUseUnicode(true);
fontProvider.defaultEncoding = BaseFont.CP1257;
I also tried setting the font, but it was not applied to the pdf.
XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
fontProvider.register(PATH_TO_TTF_FONT_FILE_HOSTED_ON_S3);
And then set the param for parseXHtml.
XMLWorkerHelper.getInstance().parseXHtml(writer, document, stream, Charset.forName("UTF-8"), fontProvider);
Is there any way I could use the PdfWriter to convert all characters correctly from html to pdf?
Trying to write heart symbol in pdf through java code .
This is my input to pdf : ❤️❤️❤️
But pdf generated is empty without anything written.
Using itext to write to pdf.
The Font used is tradegothic_lt_boldcondtwenty.ttf
OutputStream file = new FileOutputStream(fileName);
Document document = new Document(PageSize.A6);
PdfWriter writer = PdfWriter.getInstance(document, file);
document.open();
PdfLayer nested = new PdfLayer("Layer 1", writer);
PdfContentByte cb = writer.getDirectContent();
cb.beginLayer(nested);
ColumnText ct = new ColumnText(cb);
Font font = getFont();
Phrase para1 = new Phrase("❤️❤️❤️",font);
ct.setSimpleColumn(para1,38,0,260,138,15, Element.ALIGN_LEFT);
ct.go();
cb.endLayer();
document.close();
file.close();
private Font getFont() {
final String methodName = "generatePDF";
LOGGER.entering(CLASSNAME, methodName);
Font font = null;
try {
String filename = tradegothic_lt_boldcondtwenty.ttf;
FontFactory.register(filename, filename);
font = FontFactory.getFont(filename, BaseFont.CP1252, BaseFont.EMBEDDED,11.8f);
} catch(Exception exception) {
LOGGER.logp(Level.SEVERE, CLASSNAME, methodName, "Exception Occurred while fetching the Trade Gothic font." + exception);
font = FontFactory.getFont(FontFactory.HELVETICA_BOLD,11.8f);
}
return font;
}
Phrase para1 has the heart correctly. But not able to see in pdf
Below code is for writing pdf file;
BaseFont bf = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
FontSelector fs = new FontSelector();
fs.addFont(new Font(bf));
String fileName = filePath3 + "//DEVIATION_REPORT.pdf";
OutputStream file = new FileOutputStream(new File(fileName));
Font smallFont = new Font(Font.FontFamily.COURIER, 6, Font.NORMAL);
Font headerFont = new Font(Font.FontFamily.HELVETICA, 7, Font.BOLD);
Font tabFont = new Font(Font.FontFamily.HELVETICA, 5, Font.NORMAL);
Font rusFont = new Font(bf, 5);
Font blueFont = new Font(bf, 5);
blueFont.setColor(BaseColor.BLUE);
Font redFont = new Font(bf, 5);
redFont.setColor(BaseColor.RED);
String comType;
if (compType == 2)
comType = "Character";
else
comType = "Word";
Document doc = new Document();
PdfWriter.getInstance(doc, file);
doc.open();
Image image1 = Image.getInstance(cmdpath + "ScRp.jpg");
image1.setAlignment(Element.ALIGN_LEFT);
Paragraph prg = new Paragraph("Compare", smallFont);
prg.setAlignment(Element.ALIGN_RIGHT);
doc.add(image1);
doc.add(prg);
doc.add(new Paragraph("__________________________________________________"));
doc.add(new Paragraph("Passed Report"));
doc.add(new Paragraph(" "));
PdfPTable table = new PdfPTable(2);
PdfPCell cell1 = new PdfPCell(new Paragraph("No", headerFont));
cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
cell1.setPaddingBottom(5);
PdfPCell cell2 = new PdfPCell(new Paragraph("Details", headerFont));
cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
cell2.setPaddingBottom(5);
table.addCell(cell1);
table.addCell(cell2);
doc.add(table);
doc.newPage();
doc.close();
file.close();
How do I do if i want to make the pdf is non editable. I've tried to use
PdfEncryptor.encrypt(
new PdfReader(fileName),
new FileOutputStream("HelloWorldProtected.pdf"),
null,
"StrongPassword".getBytes(),
PdfWriter.AllowPrinting,
PdfWriter.STRENGTH128BITS);
but compiler stops here. I waited more than 15 minutes but nothing happen.
I even make file.setreadOnly(), but it doesn't user to save it after edit. It still allow user to edit. User can Save AS the document and replace with the non editable one.
Is there any other way we can make the file as non editable. Please advice.
You might want to use iText for such kind of work if its fine with your project. I cant see any other option as if now. I have personally used iText and it is quite robust. let me know if this helps.
Edit:
Encryption settings
http://viralpatel.net/blogs/password-protect-pdf-itext-java/
http://www.jarfinder.com/index.php/java/info/com.lowagie.text.pdf.interfaces.PdfEncryptionSettings
Try searching more on google and SO
EDIT: The long waiting of 15 min. problem might be of file write permissions on your file path.
I'm trying to create a PDF using iText and I'm having a great deal of difficulty. In short, what I want to do is:
Read in a template pdf
Make a copy in memory of the template
Draw a table on the copy
Write the copy pdf to an outputstream
So far, it's looking like this
// read in template pdf
InputStream templateStream = getServletContext().getResourceAsStream(labelsTemplate);
PdfReader reader = new PdfReader(templateStream);
// create a table in a new document
Document document = new Document();
PdfCopy copy = new PdfCopy(document, os);
document.open();
PdfPTable table = new PdfPTable(2);
PdfPCell cell;
cell = new PdfPCell(new Phrase("row 1; cell 1"));
table.addCell(cell);
cell = new PdfPCell(new Phrase("row 1; cell 2"));
table.addCell(cell);
document.add(table);
Can someone explain how I can make a copy of the template once I've used PdfReader to read it? Is there a way to write the table onto the template copy and not a new document?
For future references, here's what I've done:
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "inline;filename=\"scheduler-labels.pdf\"");
ServletOutputStream os = response.getOutputStream();
// read in template pdf
InputStream templateStream = getServletContext().getResourceAsStream(labelsTemplate);
PdfReader reader = new PdfReader(templateStream);
// make new pdf document to draw table and output to memory
Document document = new Document(reader.getPageSize(1));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);
// write table
document.open();
PdfPTable table = new PdfPTable(2);
table.setWidthPercentage(110);
PdfPCell cell;
cell = new PdfPCell(new Phrase("row 1; cell 1"));
table.addCell(cell);
cell = new PdfPCell(new Phrase("row 1; cell 2"));
table.addCell(cell);
cell = new PdfPCell(new Phrase("row 2; cell 1"));
table.addCell(cell);
cell = new PdfPCell(new Phrase("row 2; cell 2"));
table.addCell(cell);
document.add(table);
document.close();
// read in newly generated table pdf
PdfReader tableReader = new PdfReader(baos.toByteArray());
ByteArrayOutputStream baosCombined = new ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper(tableReader, baosCombined);
// get a page from the template pdf
PdfImportedPage page = stamper.getImportedPage(reader, 1);
// add to background of table pdf
PdfContentByte background;
background = stamper.getUnderContent(1);
background.addTemplate(page, 0, 0);
stamper.close();
tableReader.close();
reader.close();
// write to servlet output
baosCombined.writeTo(os);
os.flush();
os.close();
As studying the sample referenced in my comment was just what [Tuan] needed, I formulate it as an answer:
The sample Stationery.java from chapter 6 of iText in Action — 2nd Edition essentially shows how to use the contents of a given PDF as background (stationery-like) of a new PDF while filling its foreground with new content.
The central code is as follows:
public class Stationery extends PdfPageEventHelper
{
[...]
public void createPdf(String filename) throws Exception
{
// step 1
Document document = new Document(PageSize.A4, 36, 36, 72, 36);
// step 2
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
useStationary(writer);
// step 3
document.open();
// step 4
[... add content to PDF ...]
// step 5
document.close();
}
[...]
public void useStationary(PdfWriter writer) throws IOException
{
writer.setPageEvent(this);
PdfReader reader = new PdfReader(STATIONERY);
page = writer.getImportedPage(reader, 1);
}
public void onEndPage(PdfWriter writer, Document document)
{
writer.getDirectContentUnder().addTemplate(page, 0, 0);
}
[...]
}
As implicit close() calls have been removed more and more recently, the PdfReader reader instantiated in useStationary nowerdays should be stored in some variable of Stationery and closed after createPdf has executed.