I am parsing some html code using HTMLWorker in Java and then inserting it to PDF using iText. I create document by calling new Document(PageSize.A4, 40, 40, 40, 40); which should specify margin 40px on all sides, but when I insert parsed html code that contains table wider than page, right margin dont work and table reaches right border of page... All margins are ok except the right one.. any suggestions?
relevant code:
Document document = new Document(PageSize.A4, 40, 40, 40, 40);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put(HTMLWorker.FONT_PROVIDER, new MyFontFactory10());
HTMLWorker worker = new HTMLWorker(document);
worker.setProviders(map);
worker.parse(new StringReader(VARIABLE_CONTAINING_HTML_CODE));
It should work.
Can you provide info about iText version and how the HTML code looks like.
Images can make the table expand beyond margins (it´s not pixels by the way).
Try this code and see if the problem still remains. The table should not expand beyond the page margins. Tables used with HTMLWorker always get a width of 100% of its container.
Document document = new Document(PageSize.A4, 40, 40, 40, 40);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("c:/TEST.pdf"));
document.open();
HTMLWorker worker = new HTMLWorker(document);
String code = "<table border=1><tr><td>Test</td><td>Test</td></tr></table>";
worker.parse(new StringReader(code));
document.close();
Related
I have a simple piece of code that splits a sentence (named content in the code) into tokens and then writes tokens in pdf file, but each in new line.
Document document = new Document(PageSize.A4, 20, 20, 20, 20);
PdfWriter.getInstance(document, new FileOutputStream("ticket.pdf"));
document.open();
Font font = FontFactory.getFont(FontFactory.COURIER, 16, BaseColor.BLACK);
String[] tokens = content.split("\\|");
for (String token : tokens) {
Chunk chunk = new Chunk(token, font);
document.add(chunk);
document.add(Chunk.NEWLINE);
}
document.close();
But when I open the result pdf file, all of the tokens (chunks) are written over each other in the first line, like this:
Can anyone point to me what am I doing wrong here? Code is written in Spring Boot with Java 11, and iText version is 5.5.10
I want to create a pdf document using iTextpdf 7 but I don't want to use any of the default page sizes.
I want to set the width and height of my paper size but when I try to do it using Rectangle() class, it shows me errors and I can not create anything.
I've never used this library before and I don't know how to do it well.
This is an example of the code I made:
String url_file= "C:\\Users\\Mike89\\Documents\\PDFJava\\pdfFiles\\SALES\\SALEINVOICE"+id+".pdf";
PdfWriter writer = new PdfWriter(url_file);
PdfDocument pdf = new PdfDocument(writer);
Rectangle pagesize = new Rectangle(148, 350);
Document document = new Document(pdf, pagesize);
document.setMargins(2, 2, 2, 2);
Table table1 = new Table(UnitValue.createPercentArray(1)).useAllAvailableWidth().setBorder(Border.NO_BORDER);
Cell cell1;
cell1 = new Cell();
cell1.add(new Paragraph("COMPANY NAME").setTextAlignment(TextAlignment.CENTER).setFontSize(5).setBold()).setBorder(Border.NO_BORDER);
cell1.add(new Paragraph("DOCUMENT ID").setTextAlignment(TextAlignment.CENTER).setFontSize(5)).setBorder(Border.NO_BORDER);
cell1.add(new Paragraph("COMPANY ADDRESS").setTextAlignment(TextAlignment.CENTER).setFontSize(5)).setBorder(Border.NO_BORDER);
cell1.add(new Paragraph("TELEPHONE").setTextAlignment(TextAlignment.CENTER).setFontSize(5)).setBorder(Border.NO_BORDER);
table1.addCell(cell1);
document.add(table1);
document.close();
The error that netbeans shows me this:
incompatible types: Rectangle cannot be converted to PageSize
I don't want to use PageSize.A8 or A9 or A10 or anything like that. I just want to create my own page size, but I can't figure out what's wrong with my code. What can I do to solve this?
Rectangle and PageSize are different types, although PageSize extends Rectangle, but the Document constructor expects a PageSize. In Netbeans, use CTRL-SPACE to see more while working:
Please replace this
Rectangle pagesize = new Rectangle(148, 350);
Document document = new Document(pdf, pagesize);
with this:
PageSize pagesize = new PageSize(148, 350);
Document document = new Document(pdf, pagesize);
I'm using iText to create barcodes on a PDF with the same format as this one:
The problem is the the left number, the first zero digits must be smaller, while the rest of the numbers must also be bold. "T.T.C." also has to be even smaller (it doesn't have to be on another line).
I was able to rotate the number with the following code:
String price = "23000 T.T.C.";
PdfContentByte cb = docWriter.getDirectContent();
PdfTemplate textTemplate = cb.createTemplate(50, 50);
ColumnText columnText = new ColumnText(textTemplate);
columnText.setSimpleColumn(0, 0, 50, 50);
columnText.addElement(new Paragraph(price));
columnText.go();
Image image;
image = Image.getInstance(textTemplate);
image.setAlignment(Image.MIDDLE);
image.setRotationDegrees(90);
doc.add(image);
The problem is that I cannot find a way online to change the font of certain characters of the String price when it is printed on the PDF.
I have created a small Proof of Concept that results in a PDF that looks like this:
As you can see, it has text in different sizes and styles. It also has a bar code that is rotated.
Take a look at the RotatedText example:
public void createPdf(String dest) throws IOException, DocumentException {
// step 1
Document document = new Document(new Rectangle(60, 120), 5, 5, 5, 5);
// step 2
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
// step 3
document.open();
// step 4
PdfContentByte canvas = writer.getDirectContent();
Font big_bold = new Font(FontFamily.HELVETICA, 12, Font.BOLD);
Font small_bold = new Font(FontFamily.HELVETICA, 6, Font.BOLD);
Font regular = new Font(FontFamily.HELVETICA, 6);
Paragraph p1 = new Paragraph();
p1.add(new Chunk("23", big_bold));
p1.add(new Chunk("000", small_bold));
document.add(p1);
Paragraph p2 = new Paragraph("T.T.C.", regular);
p2.setAlignment(Element.ALIGN_RIGHT);
document.add(p2);
BarcodeEAN barcode = new BarcodeEAN();
barcode.setCodeType(Barcode.EAN8);
barcode.setCode("12345678");
Rectangle rect = barcode.getBarcodeSize();
PdfTemplate template = canvas.createTemplate(rect.getWidth(), rect.getHeight() + 10);
ColumnText.showTextAligned(template, Element.ALIGN_LEFT,
new Phrase("DARK GRAY", regular), 0, rect.getHeight() + 2, 0);
barcode.placeBarcode(template, BaseColor.BLACK, BaseColor.BLACK);
Image image = Image.getInstance(template);
image.setRotationDegrees(90);
document.add(image);
Paragraph p3 = new Paragraph("SMALL", regular);
p3.setAlignment(Element.ALIGN_CENTER);
document.add(p3);
// step 5
document.close();
}
This example solves all of your issues:
You want a Paragraph to use different fonts: compose a Paragraph using different Chunk objects.
You want to add extra text on top of a bar code: add the bar code to a PdfTemplate and add the extra text using ColumnText.showTextAligned() (not that you can also compose a Phrase using different Chunk objects if you need more than one font in that extra text).
You want to rotate the bar code: wrap the PdfTemplate inside an Image object and rotate the image.
You can check the result: rotated_text.pdf
I hope this helps.
I have two parts to my java project.
I need to populate the fields of a pdf
I need to add a table below the populated section on the blank area of the page (and this table needs to be able to rollover to the next page).
I am able to do these things separately (populate the pdf and create a table). But I cannot effectively merge them. I have tried doing a doc.add(table) which will result in the table being on the next page of the pdf, which I don't want.
I essentially just need to be able to specify where the table starts on the page (so it wouldn't overlap the existing content) and then stamp the table onto the existing pdf.
My other option if this doesn't work is trying to add fields to the original pdf that will be filled by the table contents (so it will instead be a field-based table).
Any suggestions?
EDIT:
I'm new to iText and have not used columntext before, but I'm trying to test it out in the following code but the table is not being displayed. I looked at other columntext examples and I have not seen exactly where the columntext is added back into the pdf.
//CREATE FILLED FORM PDF
PdfReader reader = new PdfReader(sourcePath);
PdfStamper pdfStamper = new PdfStamper(reader, new FileOutputStream(destPath));
pdfStamper.setFormFlattening(true);
AcroFields form = pdfStamper.getAcroFields();
form.setField("ID", "99999");
form.setField("ADDR1", "425 Test Street");
form.setField("ADDR2", "Test, WA 91334");
form.setField("PHNBR", "(999)999-9999");
form.setField("NAME", "John Smith");
//CREATE TABLE
PdfPTable table = new PdfPTable(3);
Font bfBold12 = new Font(FontFamily.HELVETICA, 12, Font.BOLD, new BaseColor(0, 0, 0));
insertCell(table, "Table", Element.ALIGN_CENTER, 1, bfBold12);
table.completeRow();
ColumnText column = new ColumnText(pdfStamper.getOverContent(1));
column.addElement(table);
pdfStamper.close();
reader.close();
Please take a look at the AddExtraTable example. It's a simplification of the AddExtraPage example written in answer to the question How to continue field output on a second page?
That question is almost an exact duplicate of your question, with as only difference the fact that your requirement is easier to achieve.
I simplified the code like this:
public void manipulatePdf(String src, String dest) throws DocumentException, IOException {
PdfReader reader = new PdfReader(src);
Rectangle pagesize = reader.getPageSize(1);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
AcroFields form = stamper.getAcroFields();
form.setField("Name", "Jennifer");
form.setField("Company", "iText's next customer");
form.setField("Country", "No Man's Land");
PdfPTable table = new PdfPTable(2);
table.addCell("#");
table.addCell("description");
table.setHeaderRows(1);
table.setWidths(new int[]{ 1, 15 });
for (int i = 1; i <= 150; i++) {
table.addCell(String.valueOf(i));
table.addCell("test " + i);
}
ColumnText column = new ColumnText(stamper.getOverContent(1));
Rectangle rectPage1 = new Rectangle(36, 36, 559, 540);
column.setSimpleColumn(rectPage1);
column.addElement(table);
int pagecount = 1;
Rectangle rectPage2 = new Rectangle(36, 36, 559, 806);
int status = column.go();
while (ColumnText.hasMoreText(status)) {
status = triggerNewPage(stamper, pagesize, column, rectPage2, ++pagecount);
}
stamper.setFormFlattening(true);
stamper.close();
reader.close();
}
public int triggerNewPage(PdfStamper stamper, Rectangle pagesize, ColumnText column, Rectangle rect, int pagecount) throws DocumentException {
stamper.insertPage(pagecount, pagesize);
PdfContentByte canvas = stamper.getOverContent(pagecount);
column.setCanvas(canvas);
column.setSimpleColumn(rect);
return column.go();
}
As you can see, the main differences are:
We create a rectPage1 for the first page and a rectPage2 for page 2 and all pages that follow. That's because we don't need a full page on the first page.
We don't need to load a PdfImportedPage, instead we're just adding blank pages of the same size as the first page.
Possible improvements: I hardcoded the Rectangle instances. It goes without saying that rect1Page depends on the location of your original form. I also hardcoded rect2Page. If I had more time, I would calculate rect2Page based on the pagesize value.
See the following questions and answers of the official FAQ:
How to add a table on a form (and maybe insert a new page)?
How to continue field output on a second page?
I am trying to apply float property to a div in itext. The content is an HTML content
Document document = new Document(PageSize.A4, 36, 72, 108, 180);
PdfWriter.getInstance(document, servletOutputStream);
document.open();
HTMLWorker htmlWorker = new HTMLWorker(document);
StyleSheet style = new StyleSheet();
style.loadStyle("class-name", "float", "left");
htmlWorker.setStyleSheet(style);
htmlWorker.parse(new StringReader(stringBuilder.toString()));
The above code doesn't work for float, but for other properties like size,color,etc.
What could be the possible solution.
HTMLWorker has been discontinued in favor of XML Worker.
The project :
http://sourceforge.net/projects/xmlworker/
The demo :
http://demo.itextsupport.com/xmlworker/
The documentation :
http://demo.itextsupport.com/xmlworker/itextdoc/index.html