I am developing a simple invoice generation software for my store.
I am trying to print the final things in a PDF using iText but I am not able to work properly with the method setSimpleColumn that I am using with ColumnText.
I am not able to understand the concept of llx,lly,urx,ury but I am trying through hit n try method but not able to get any result
This is my code
public class CreateInvoicePdf {
public static final String DEST="C:\\Users\\sanju\\Desktop\\resul.pdf";
public static void main(String args[]) throws FileNotFoundException, DocumentException
{
File file = new File (DEST);
file.getParentFile().mkdirs();
new CreateInvoicePdf().createPdf(DEST);
}
public void createPdf(String dest) throws FileNotFoundException, DocumentException
{
Document d = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(d, new FileOutputStream(dest));
d.open();
PdfContentByte can = writer.getDirectContent();
Paragraph companyDetails = new Paragraph("CLIMAX EXCLUSIVE\nShop No. G1 G2 Mohan Bazar\nCentral Market Ashok Vihar\nNew Delhi-110052");
Paragraph invoiceDetails = new Paragraph("Invoice No : 1234\nDate : 10/05/2018\nPay : CASH");
PdfPTable itemTable = new PdfPTable(9);
itemTable.addCell("1");
itemTable.addCell("Shirt");
itemTable.addCell("1999");
itemTable.addCell("1");
itemTable.addCell("1999");
itemTable.addCell("12");
itemTable.addCell("1500");
itemTable.addCell("250");
itemTable.addCell("250");
ColumnText ct = new ColumnText(can);
ct.setSimpleColumn(100,200,300,400);
ct.addElement(companyDetails);
ct.go();
ct.setSimpleColumn(400,200,600,700);
ct.addElement(invoiceDetails);
ct.go();
ct.setSimpleColumn(100, 700, 500, 500);
ct.addElement(itemTable);
ct.go();
d.close();
writer.close();
}}
and the output I am getting is weird.
I want the company details and address to be on the upper left corner
The invoice number date and details at upper right corner
The invoice items table below these
Related
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();
}
I have a pdf template on which I have to write, say the number of person visited a place along with other information. The pdf template has 25 rows.
So, if the count of people visiting the place is more than 25, I need to append a copy of the same pdf template as page 2 which will contain the entry for person 26 till 50. My current set up is :
reader = new PdfReader(PATH_TO_PDF_TEMPLATE);
stamper = new PdfStamper(reader, WRITTEN_FILE_PATH);
I want to use the same PDF Template again and append to the written 1st page in case the number of people is more than 25.
Here is a simple example of table which has 21 rows per page. You can set cell.setFixedHeight(33.68f) (bigger than 33.68) cell height to get 25 rows per page.
public class SimpleTable {
public static final String DEST = "C:\\Users\\krezus\\Desktop\\simple_table.pdf";
public static void main(String[] args) throws IOException,
DocumentException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new SimpleTable5().createPdf(DEST);
}
public void createPdf(String dest) throws IOException, DocumentException {
Document document = new Document(PageSize.A4);
PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
PdfPTable table = new PdfPTable(5);
table.setWidthPercentage(100);
table.setSkipFirstHeader(true);
System.out.println(PageSize.A4.getHeight()/25);
table.setSkipLastFooter(true);
for (int i = 0; i < 350; i++) {
PdfPCell celltable = new PdfPCell(new Phrase(Integer.toString(i)));
celltable.setFixedHeight(33.68f);
table.addCell(celltable);
}
document.add(table);
document.close();
}
}
I have used PdfPageEvent.onStartPage() and onEndPage().
writer = PdfWriter.getInstance(document, exportOutputStream);
writer.setPageEvent(pageEventHandler);
am generating check-box inside Itext PDF Table but inside table check box is not generating its generating outside table.could please help me how to append that check box into PDF table.could you please help me out.
Below is my code:
Class A{
public void createFourColumnBody() throws DocumentException, FileNotFoundException {
com.itextpdf.text.Document document = new com.itextpdf.text.Document(PageSize.A4);
com.itextpdf.text.pdf.PdfWriter writer1 = PdfWriter.getInstance(document, new FileOutputStream("D:\\PDF_Java.pdf", false));
document.open();
float[] widths = new float[]{30f, 30f};
com.itextpdf.text.pdf.PdfPTable table = new com.itextpdf.text.pdf.PdfPTable(widths);
table.setWidthPercentage(100);
table.setHorizontalAlignment(Element.ALIGN_LEFT);
PdfFormField checkboxGroupField = PdfFormField.createCheckBox(writer1);
PdfPCell cell = table.getDefaultCell();
PdfPCell cell12;
cell = new PdfPCell(new Paragraph("checkbox3"));
table.addCell(cell);
cell12 = new PdfPCell(table.getDefaultCell());
cell12.setCellEvent(new CellField(writer1, checkboxGroupField, true));
table.addCell(cell12);
writer1.addAnnotation(checkboxGroupField);
document.add(table);
document.close();
}
public static void main(String[] args) throws DocumentException, FileNotFoundException {
A a1 = new A();
a1.createFourColumnBody();
}
}
This is explained in the CheckboxCell example. That example was written in answer to Resizing a form field in iTextSharp, but it also answers your question.
Note that your question remained unanswered for so long because you used the [itextpdf] tag instead of [itext] or [itextsharp]. I only found this question by coincidence.
I am getting a The document has no pages. runtime error in this program...
public class Windows {
public static void main(String[] args) throws FileNotFoundException, DocumentException {
java.io.File f = new java.io.File("c:/temp/text.pdf");
java.io.FileOutputStream fo = new java.io.FileOutputStream(f);
com.itextpdf.text.Document d = new com.itextpdf.text.Document(PageSize.A5, 50, 50, 50, 50);
PdfWriter pw = PdfWriter.getInstance(d, fo);
d.open();
Boolean b0 = d.newPage();
Boolean b1 = d.addAuthor("Tamil Selvan");
d.addCreator("Tamil Selvan");
d.addHeader("Tamil Selvan Header name", "Header Content");
d.addKeywords("These are the keywords for the document");
d.addSubject("These are the subjects for the Document");
d.addTitle("The Title Of the Document");
d.close();
System.out.println("Is the Documnet is Opened "+b0);
System.out.println("Is the Documnet is Working "+b1);
};
}
How can I run this?
I believe the problem here is that you have provided metadata for the pdf, but no actual body or content for the pdf.
For example, you can try
d.add(new Paragraph("Some random text"));
and seeing if this addresses the error you are facing.
Is there a way I can edit a PDF from Java?
I have a PDF document which contains placeholders for text that I need to be replaced using Java, but all the libraries that I saw created PDF from scratch and small editing functionality.
Is there anyway I can edit a PDF or is this impossible?
You can do it with iText. I tested it with following code. It adds a chunk of text and a red circle over each page of an existing PDF.
/* requires itextpdf-5.1.2.jar or similar */
import java.io.*;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;
public class AddContentToPDF {
public static void main(String[] args) throws IOException, DocumentException {
/* example inspired from "iText in action" (2006), chapter 2 */
PdfReader reader = new PdfReader("C:/temp/Bubi.pdf"); // input PDF
PdfStamper stamper = new PdfStamper(reader,
new FileOutputStream("C:/temp/Bubi_modified.pdf")); // output PDF
BaseFont bf = BaseFont.createFont(
BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); // set font
//loop on pages (1-based)
for (int i=1; i<=reader.getNumberOfPages(); i++){
// get object for writing over the existing content;
// you can also use getUnderContent for writing in the bottom layer
PdfContentByte over = stamper.getOverContent(i);
// write text
over.beginText();
over.setFontAndSize(bf, 10); // set font and size
over.setTextMatrix(107, 740); // set x,y position (0,0 is at the bottom left)
over.showText("I can write at page " + i); // set text
over.endText();
// draw a red circle
over.setRGBColorStroke(0xFF, 0x00, 0x00);
over.setLineWidth(5f);
over.ellipse(250, 450, 350, 550);
over.stroke();
}
stamper.close();
}
}
I modified the code found a bit and it was working as follows
public class Principal {
public static final String SRC = "C:/tmp/244558.pdf";
public static final String DEST = "C:/tmp/244558-2.pdf";
public static void main(String[] args) throws IOException, DocumentException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new Principal().manipulatePdf(SRC, DEST);
}
public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
PdfDictionary dict = reader.getPageN(1);
PdfObject object = dict.getDirectObject(PdfName.CONTENTS);
PdfArray refs = null;
if (dict.get(PdfName.CONTENTS).isArray()) {
refs = dict.getAsArray(PdfName.CONTENTS);
} else if (dict.get(PdfName.CONTENTS).isIndirect()) {
refs = new PdfArray(dict.get(PdfName.CONTENTS));
}
for (int i = 0; i < refs.getArrayList().size(); i++) {
PRStream stream = (PRStream) refs.getDirectObject(i);
byte[] data = PdfReader.getStreamBytes(stream);
stream.setData(new String(data).replace("NULA", "Nulo").getBytes());
}
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.close();
reader.close();
}
}
Take a look at iText and this sample code
Take a look at aspose and this sample code
I've done this using LibreOffice Draw.
You start by manually opening a pdf in Draw, checking that it renders OK, and saving it as a Draw .odg file.
That's a zipped xml file, so you can modify it in code to find and replace the placeholders.
Next (from code) you use a command line call to Draw to generate the pdf.
Success!
The main issue is that Draw doesn't handle fonts embedded in a pdf. If the font isn't also installed on your system - then it will render oddly, as Draw will replace it with a standard one that inevitably has different sizing.
If this approach is of interest, I'll put together some shareable code.