Itext 7.1.16 - adding Two Paragraphs dont work - java

i try to create PDF Document but i'am not able to Create a Document with 2 Paragraphs.
It just show the first one added:
Here is my code for reproducing:
public void createBillingDocument(List<PDFData> datas) {
datas.forEach(data -> {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PdfWriter writer = new PdfWriter(outputStream);
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf,PageSize.A4);
document.add(new Paragraph("Muh"));
document.add(new Paragraph("Kuh"));
document.close();
pdf.close();
writer.close();
outputStream.close();
fileAccess.storeFile(outputStream.toString(), "test/" + "Name.pdf");
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
Has anyone the same Problem an found a Solution?
Regards
Edit:
One Strange thing is, if i make a Breake betwenn it both Paragraphs are shown. Each one one Page.
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PdfWriter writer = new PdfWriter(outputStream);
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf,PageSize.A4);
document.add(new Paragraph("Muh"));
document.add(new AreaBreak());
document.add(new Paragraph("Kuh"));
document.close();
pdf.close();
writer.close();
outputStream.close();
fileAccess.storeFile(outputStream.toString(), "test/" + "Name.pdf");
} catch (IOException e) {
throw new RuntimeException(e);
}

Ok found out. #mkl was right. The Problem lies somewhere in "save the Document as String". Chaged it to ByteArray and voila it worked :)
Thanks for your Time!

Related

ExceptionConverter: java.io.IOException: Stream Closed when trying to create a PDF using iText

I'm working on PDF related project and I want to create a PDF from the existing PDF.
all things are done but when I created a final PDF at that time this exception was thrown at the line of document.close(); at the method of savePDF which describe below.
Create new PDF from existing PDF adding PdfImportedPage.
here is my code
The app crashes only when we add a new page
private void createAndAddPage(Bitmap bitmap) {
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Document document = new Document();
File file = getPdfFile();
FileOutputStream fileOutputStream = new FileOutputStream(file);
PdfWriter pdfWriter = PdfWriter.getInstance(document, fileOutputStream); // Change pdf's name.
document.open();
Image image = Image.getInstance(byteArray); // Change image's name and extension.
float scaler = ((document.getPageSize().getWidth() - document.leftMargin()
- document.rightMargin() - 0) / image.getWidth()) * 100; // 0 means you have no indentation. If you have any, change it.
image.scalePercent(scaler);
image.setAlignment(Image.ALIGN_CENTER);
document.add(image);
document.close();
PdfReader pdfReader = new PdfReader(file.getPath());
PdfImportedPage pdfImportedPage = pdfWriter.getImportedPage(pdfReader, 1);
pageAdjustmentAdapter.AddPage(new PageAjdustAdapter.PdfPage(pdfImportedPage, bitmap));
} catch (Exception e) {
e.printStackTrace();
}
}
method when saves a final PDF(crash happens in this method)
private void savePDF(PageAjdustAdapter pageAdjustment) {
mPDFpages = pageAdjustment.getUpdatedList();
try {
pdfWriter.setPageEvent(new RotateEvent());
document.open();
PdfContentByte pdfContentByte = pdfWriter.getDirectContent();
for (int i = 0; i < mPDFpages.size(); i++) {
pdfContentByte.addTemplate(mPDFpages.get(i).page, 0, 0);
document.newPage();
}
} catch (Exception e) {
Log.d(TAG, "run: -> " + e.getMessage());
e.printStackTrace();
} finally {
if (document.isOpen()) document.close();
actionListener.onEnd("Success");
}
}
logcat
ExceptionConverter: java.io.IOException: Stream Closed
at java.io.FileOutputStream.write(FileOutputStream.java:391)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
at java.io.BufferedOutputStream.write(BufferedOutputStream.java:121)
at java.io.FilterOutputStream.write(FilterOutputStream.java:103)
at com.itextpdf.text.pdf.OutputStreamCounter.write(OutputStreamCounter.java:104)
at com.itextpdf.text.pdf.PRStream.toPdf(PRStream.java:244)
at com.itextpdf.text.pdf.PdfIndirectObject.writeTo(PdfIndirectObject.java:157)
at com.itextpdf.text.pdf.PdfWriter$PdfBody.write(PdfWriter.java:402)
at com.itextpdf.text.pdf.PdfWriter$PdfBody.add(PdfWriter.java:380)
at com.itextpdf.text.pdf.PdfWriter$PdfBody.add(PdfWriter.java:359)
at com.itextpdf.text.pdf.PdfWriter.addToBody(PdfWriter.java:854)
at com.itextpdf.text.pdf.PdfReaderInstance.writeAllVisited(PdfReaderInstance.java:160)
at com.itextpdf.text.pdf.PdfReaderInstance.writeAllPages(PdfReaderInstance.java:176)
at com.itextpdf.text.pdf.PdfWriter.addSharedObjectsToBody(PdfWriter.java:1368)
at com.itextpdf.text.pdf.PdfWriter.close(PdfWriter.java:1251)
at com.itextpdf.text.pdf.PdfDocument.close(PdfDocument.java:901)
at com.itextpdf.text.Document.close(Document.java:415)
at com.mobilix.docscanner.PageAdjustment$8.run(PageAdjustment.java:233)
at java.lang.Thread.run(Thread.java:923)
In createAndAddPage you import the page into the wrong PdfWriter:
Document document = new Document();
File file = getPdfFile();
FileOutputStream fileOutputStream = new FileOutputStream(file);
PdfWriter pdfWriter = PdfWriter.getInstance(document, fileOutputStream); // Change pdf's name.
document.open();
[...]
document.close();
PdfReader pdfReader = new PdfReader(file.getPath());
PdfImportedPage pdfImportedPage = pdfWriter.getImportedPage(pdfReader, 1);
Here you import the new page into the PdfWriter used for creating that same new page. You instead have to import it into the PdfWriter in which you eventually want to use the pdfImportedPage.

How to generate a pdf to a variable instead of a file?

I am creating a pdf file and storing it in a directory. I now want to pass back the pdf data so the user can download it to their preferred directory (i.e., no longer create the file in the directory). How do I create the "pdfData" to pass back please?
I understand that it would involve replaceing "new FileOutputStream(FILE)" with the name of the variable to store the data in; however, I can not work it out or find an example online.
I have:
String filePath = System.getProperty("user.home") + "\\Documents\\"+fileName; //Test use
Document document = new Document(PageSize.A4, 72f, 72f, 72f, 72f);
try {
PdfWriter.getInstance(document, new FileOutputStream(FILE));
document.open();
addMetaData(document);
addImages(document);
addTitlePage(document, recipeDetails, recipeName, servings, servingSize);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
//return pdfData;
To show what mkl suggested merged in with your code:
String filePath = System.getProperty("user.home") + "\\Documents\\"+fileName; //Test use
Document document = new Document(PageSize.A4, 72f, 72f, 72f, 72f);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);
document.open();
addMetaData(document);
addImages(document);
addTitlePage(document, recipeDetails, recipeName, servings, servingSize);
document.close();
byte[] pdfData = baos.toByteArray();
return pdfData;
} catch (Exception e) {
e.printStackTrace();
}
The pdfData is a byte[] (byte array). This can be directly streamed/stored anywhere as the actual pdf. Just keep in mind that this is writing the PDF into memory, so you have scalability issue if doing lots of large PDFs concurrently.
I hope that helps.

IText html to pdf wrapping line

Hello I'm creating javafx app with iText. I have html editor to write text and I want to create pdf from it. Everything works but when I have a really long line that is wrapped in html editor, in pdf it isn't wrapped, its out of page, how can I set wrapping page? here is my code:
PdfWriter writer = null;
try {
writer = new PdfWriter("doc.pdf");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Initialize PDF document
PdfDocument pdf = new PdfDocument(writer);
// Initialize document
Document document = new Document(pdf, PageSize.A4);
List<IElement> list = null;
try {
list = HtmlConverter.convertToElements(editor.getHtmlText());
} catch (IOException e) {
e.printStackTrace();
}
// add elements to document
for (IElement p : list) {
document.add((IBlockElement) p);
}
// close document
document.close();
I also want to set line spacing for this text
Thank you for help
I don't get any errors for the following code:
public class stack_overflow_0008 extends AbstractSupportTicket{
private static String LONG_PIECE_OF_TEXT =
"Once upon a midnight dreary, while I pondered, weak and weary," +
"Over many a quaint and curious volume of forgotten lore—" +
"While I nodded, nearly napping, suddenly there came a tapping," +
"As of some one gently rapping, rapping at my chamber door." +
"Tis some visitor,” I muttered, “tapping at my chamber door—" +
"Only this and nothing more.";
public static void main(String[] args)
{
PdfWriter writer = null;
try {
writer = new PdfWriter(getOutputFile());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Initialize PDF document
PdfDocument pdf = new PdfDocument(writer);
// Initialize document
Document document = new Document(pdf, PageSize.A4);
List<IElement> list = null;
try {
list = HtmlConverter.convertToElements("<p>" + LONG_PIECE_OF_TEXT + "</p>");
} catch (IOException e) {
e.printStackTrace();
}
for (IElement p : list) {
document.add((IBlockElement) p);
}
document.close();
}
}
The document is a single (A4) page PDF with one string neatly wrapped.
I think perhaps the content of your string is to blame?
Could you post the HTML you get from this editor object?
Update:
Using the code from this answer on the HTML shared in a new comment to the question, I get the following result:
As you can see, the content is distributed over two lines. No content "falls off the page."

Java iText using Lithuanian letters

I am trying to create PDF file with java and I need to use Lithuanian letters within file. I tried to use html code and use htmlWorker to parse it, however it does not work on most letters(it works on some). If anyone could help me with this I would gladly appreciate it.
try {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(pathy));
document.open();
HTMLWorker htmlWorker = new HTMLWorker(document);
String s = ("<html>ĄąĘęŪūČŠ"
+ "ŽčšžĖėĮįŲų</html>");
htmlWorker.parse(new StringReader(s));
document.close();
}
catch(Exception e2){
}
I solved my issue by using unicode, not sure why it doesn't work with html code still...
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream(pathy));
document.open();
BaseFont bfComic = BaseFont.createFont("c:\\windows\\fonts\\arial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
document.add(new Paragraph("ąĄčČęĘėĖįĮšŠųŲūŪžŽ", new Font(bfComic, 12)));
} catch (Exception e2) {
System.err.println(e2.getMessage());
}
document.close();

iText rotate() won't orient the first page

Everything I have read regarding iText says you should be able to set the page size and then create a new page. But for some reason when I try this my first page isn't rotated. But my second is. Any ideas?
response.setContentType("application/pdf");
Document document = new Document();
try{
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
PdfWriter.getInstance(document, buffer);
document.open();
//Start a new page
document.setPageSize(PageSize.LETTER.rotate()); // 11" x 8.5" new Rectangle(792f, 612f)
document.newPage();
Paragraph topText = new Paragraph();
// add some content here...
document.close();
DataOutput dataOutput = new DataOutputStream(response.getOutputStream());
byte[] bytes = buffer.toByteArray();
response.setContentLength(bytes.length);
for(int i = 0; i < bytes.length; i++) {
dataOutput.writeByte(bytes[i]);
}
} catch (DocumentException e) {
e.printStackTrace();
}
document.newPage() really means "finish the current page and open a new one". This implies that after you open() a document, you already have a blank page (with whatever size the document had set before) ready.
You should set your page size before opening the document:
document.setPageSize(PageSize.LETTER.rotate());
document.open();

Categories

Resources