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.
Related
I am reading the text from PDF file using PDFBOX. I am able to read properly using "Rectangle2D". But issue where results shows one by one. Instead i want show in Transpose view.
Current view
PO-00145678
Vendor : AQ-00067
Date...................................: 5/10/2021
Expected DeliveryDate...: 6/10/2021
Expected results
In one line
PO-00145678 Vendor : AQ-00067 Date...................................: 5/10/2021 Expected DeliveryDate...: 6/10/2021
Code using
public class PDFBoxReadFromFile {
public static void main(String[] args) throws Exception {
try (PDDocument document = PDDocument.load(new File("C:\\Users\\ed\\Documents\\test2.pdf"))) {
if (!document.isEncrypted()) {
PDFTextStripperByArea stripper = new PDFTextStripperByArea();
stripper.setSortByPosition(true);
Rectangle2D rect4 = new Rectangle2D.Double(210, 160, 230, 25);
Rectangle rect1 = new Rectangle(55, 290, 225, 17);
Rectangle2D rect2 = new Rectangle2D.Double(281, 255, 255, 20);
Rectangle2D rect3 = new Rectangle2D.Double(2, 365, 660, 1900);
stripper.addRegion("class2", rect1);
stripper.addRegion("class3", rect2);
stripper.addRegion("class4", rect3);
stripper.addRegion("class5", rect4);
PDPage firstPage = document.getPages().get(0);
stripper.extractRegions(firstPage);
System.out.println(stripper.getTextForRegion("class5"));
System.out.println(stripper.getTextForRegion("class2"));
System.out.println(stripper.getTextForRegion("class3"));
System.out.println(stripper.getTextForRegion("class4"));
File file = new File("C:/Users/ed/eclipse-workspace/pdfboxreadfromfile/file.txt");
FileWriter fw = new FileWriter(file);
PrintWriter pw = new PrintWriter(fw);
pw.println(stripper.getTextForRegion("class5"));
pw.println(stripper.getTextForRegion("class2"));
pw.println(stripper.getTextForRegion("class3"));
pw.println(stripper.getTextForRegion("class4"));
pw.close();
}
} catch (IOException e) {
System.err.println("Exception while trying to read pdf document - " + e);
}
}
Second type but no luck
System.out.print(stripper.getTextForRegion ( "class5" ) + (stripper.getTextForRegion( "class2")));
results
It should be like PO-003334823 Vendor : WL-00051
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 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
I am generating PDF file using ItextPdf but I am getting an exception on this line canvas.addImage(background, width, 0,0, height, 20, 430); i.e. The type java.awt.geom.AffineTransform cannot be resolved. It is indirectly referenced from required .class files . On this line I am trying to set background image. Please help me out from this exception.
public void createPDF() throws NumberFormatException, ParseException
{
list1.add("I-Tax Number : ");
list1.add("Category : ");
list1.add("Service : ");
list1.add("Number : ");
list1.add("Amount : ");
list1.add("Status : ");
list2.add(iTaxNumber);
list2.add("Bill Payment");
list2.add("Idea Postapid");
list2.add("9644212111");
list2.add("100");
list2.add("SUCCESS");
Font trfont = new Font(FontFamily.TIMES_ROMAN, 12, Font.BOLDITALIC,
new BaseColor(130, 130, 140));
Font otherfont = new Font(FontFamily.TIMES_ROMAN, 12, Font.NORMAL,
new BaseColor(160, 160, 160));
Font datefont = new Font(FontFamily.TIMES_ROMAN, 12, Font.BOLD,
new BaseColor(130, 130, 140));
Font thanksFont = new Font(FontFamily.TIMES_ROMAN, 14, Font.BOLDITALIC,
new BaseColor(130, 130, 140));
Document doc = new Document(new Rectangle(792, 612));
try {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();
Log.d("PDFCreator", "PDF Path: " + path);
File file = new File(dir, "demo98989.pdf");
FileOutputStream fOut = new FileOutputStream(file);
PdfWriter docPdfWriter = PdfWriter.getInstance(doc, fOut);
Paragraph fromTotoDate = new Paragraph("Date : 25-oct-2015", datefont);
fromTotoDate.setAlignment(Element.ALIGN_RIGHT);
fromTotoDate.setIndentationRight(5);
doc.addAuthor("betterThanZero");
doc.addCreationDate();
doc.addProducer();
doc.addCreator("www.xyz.com");
doc.setPageSize(PageSize.A4);
doc.open();
PdfPTable table = setTable(list1, list2);
Paragraph trId = new Paragraph("Transaction Id : 889879899", trfont);
trId.setAlignment(Element.ALIGN_RIGHT);
trId.setIndentationRight(65);
Paragraph p = new Paragraph("\n\n\n\n");
Paragraph nextline = new Paragraph("\n");// for blank line
doc.add(fromTotoDate);
doc.add(p);
doc.add(trId);
int list1size = list1.size();
String size = String.valueOf(list1size);
Image trDetails_Icon;
Bitmap bmp = BitmapFactory.decodeResource(getBaseContext().getResources(),R.drawable.trreceipt);
ByteArrayOutputStream streamTrReceipt = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, streamTrReceipt);
trDetails_Icon = Image.getInstance(streamTrReceipt.toByteArray());
trDetails_Icon.scaleAbsolute(445f, 238f);
trDetails_Icon.setAbsolutePosition(76, 516);
doc.add(trDetails_Icon);
doc.add(nextline);
doc.add(table);
Paragraph thanktouMessage = new Paragraph("Thanks for Being with Us ! ", thanksFont);
thanktouMessage.setAlignment(Element.ALIGN_CENTER);
doc.add(nextline);
doc.add(thanktouMessage);
Font contFont = new Font(FontFamily.TIMES_ROMAN, 10, Font.NORMAL,
new BaseColor(130, 130, 140));
doc.add(nextline);
Paragraph cont = new Paragraph("For more info contact us", contFont);
cont.setAlignment(Element.ALIGN_RIGHT);
cont.setIndentationRight(20);
doc.add(cont);
System.out.println("list2.get(1) = "+list2.get(1));
float width;
float height;
Image background;
Bitmap bmp1 = BitmapFactory.decodeResource(getBaseContext().getResources(),R.drawable.trans);
ByteArrayOutputStream streamTrReceipt1 = new ByteArrayOutputStream();
bmp1.compress(Bitmap.CompressFormat.PNG, 100, streamTrReceipt1);
System.out.println("list2.get(1) = "+list2.get(1)+"ELSE");
width = PageSize.A4.getWidth()-40;
height = (PageSize.A4.getHeight()/2)-25;
background = Image.getInstance(streamTrReceipt1.toByteArray());
PdfContentByte canvas = docPdfWriter.getDirectContentUnder();
canvas.addImage(background, width, 0,0, height, 20, 430);
Toast.makeText(getApplicationContext(), "Created...", Toast.LENGTH_LONG).show();
} catch (DocumentException de) {
Log.e("PDFCreator", "DocumentException:" + de);
} catch (IOException e) {
Log.e("PDFCreator", "ioException:" + e);
}
finally
{
doc.close();
}
}
You are using the wrong iText version. You should use iTextG instead of the "plain Java" iText version. As an Android developer, you know that it's forbidden to use java.awt (and javax.nio,...) classes on Android.
The "plain Java" iText uses classes that aren't whitelisted on Android (e.g. in the PdfGraphics2D class). That's why we've created iTextG. iTextG is essentially identical to iText, except that we've removed all dependencies on the "forbidden classes" (and java.awt.geom.AffineTransform is one of those classes).
There is slightly less functionality in iTextG (we had to drop PdfGraphics2D), but at first sight, I don't see anything that isn't supported in iTextG in your code.
Long story short: replace iText with its Android port iTextG and your problem will be solved.
Below is the code to write PDF using Java.
Code
public class PDFTest {
public static void main(String args[]) {
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
try {
File file = new File("C://test//itext-test.pdf");
FileOutputStream fileout = new FileOutputStream(file);
PdfWriter.getInstance(document, fileout);
document.addAuthor("Me");
document.addTitle("My iText Test");
document.open();
Chunk chunk = new Chunk("iText Test");
Paragraph paragraph = new Paragraph();
String test = "și";
String test1 = "şi";
if (test.equalsIgnoreCase(test1)) {
// System.out.println("equal ignore case true");
paragraph.add(test + " New Font equal with Old Font");
} else {
// System.out.println("equal ignore case X true");
paragraph.add(test1 + " New Font Not equal with Old Font");
}
paragraph.setAlignment(Element.ALIGN_CENTER);
document.add(paragraph);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
When I test with Romanian language, I found that "ș" is missing in created PDF.
The Document appears like below:
Any advice or references links regarding this issue is highly appreciated.
**EDITED**
I've use unicode example like below and the output is still same. "ș" is still missing.
Code
static String RESULT = "C://test/itext-unicode4.pdf";
static String FONT = "C://Users//PenangIT//Desktop//Arial Unicode.ttf";
public static void main(String args[])
{
try
{
Document doc = new Document();
PdfWriter.getInstance(doc, new FileOutputStream(RESULT));
doc.open();
BaseFont bf;
bf = BaseFont.createFont(FONT,BaseFont.IDENTITY_H,BaseFont.EMBEDDED);
doc.add(new Paragraph("Font : "+bf.getPostscriptFontName()+" with encoding: "+bf.getEncoding()));
doc.add(new Paragraph(" TESTING "));
doc.add(new Paragraph(" TESTING 1 și "));
doc.add(new Paragraph(" TESTING 2 şi "));
doc.add(Chunk.NEWLINE);
doc.close();
}
catch(Exception ex)
{
}
The Output looks like this
It same for encode as well. The "ș" is still missing.
Please take a look at this PDF: encoding_example.pdf (*)
It contains all kinds of characters that aren't present in the default font Helvetica (which is the default font you're using as you're not defining any other font).
In the EncodingExample source, we use arialbd.ttf with a specific encoding, resulting in the use of a simple font in the PDF. In the UnicodeExample source, we use IDENTITY_H as encoding, resulting in the use of a composite font in the PDF.
I've adapted your code, because I see that you didn't understand my answer:
BaseFont bf = BaseFont.createFont(FONT,BaseFont.IDENTITY_H,BaseFont.EMBEDDED);
doc.add(new Paragraph(" TESTING 1 și ", new Font(bf, 12)));
doc.add(new Paragraph(" TESTING 2 \u015Fi ", new Font(bf, 12)));
Do you see the difference? In your code, you create bf, but you aren't using that object anywhere.
(* )Note: pdf.js can't interpret some glyphs because pdf.js doesn't support simple fonts with a special encoding; these glypgh show up correctly in Adobe Reader and Chrome PDF viewer. If you want to be safe, use composite fonts, because pdf.js can render those glyphs correctly: unicode_example.pdf