I want to create a new pdf for each iteration of the loop so i wrote the below code in java:
PdfWriter writer;
PdfDocument pdf;
Document document;
int i=0;
while(condition){
writer = new PdfWriter("test_"+Integer.toString(i)+".pdf");
pdf = new PdfDocument(writer);
document = new Document(pdf);
//content code here
document.close()
i++;
}
i get the below exception on the line of the document.close() command:
Exception in thread "main" com.itextpdf.kernel.PdfException: Pdf
indirect object belongs to other PDF document. Copy object to current
pdf document. at
com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:184)
at
com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:174)
at
com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:104)
at
com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:176)
at
com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:104)
at
com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:176)
at
com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:104)
at com.itextpdf.kernel.pdf.PdfWriter.writeToBody(PdfWriter.java:335)
at com.itextpdf.kernel.pdf.PdfWriter.flushObject(PdfWriter.java:243)
at
com.itextpdf.kernel.pdf.PdfDocument.flushObject(PdfDocument.java:1446)
at com.itextpdf.kernel.pdf.PdfObject.flush(PdfObject.java:155) at
com.itextpdf.kernel.pdf.PdfObject.flush(PdfObject.java:128) at
com.itextpdf.kernel.pdf.PdfObjectWrapper.flush(PdfObjectWrapper.java:96)
at com.itextpdf.kernel.pdf.PdfPage.flush(PdfPage.java:489) at
com.itextpdf.kernel.pdf.PdfPage.flush(PdfPage.java:448) at
com.itextpdf.kernel.pdf.PdfDocument.close(PdfDocument.java:739) at
com.itextpdf.layout.Document.close(Document.java:120) at
gr.moh.Pdf.main(Pdf.java:224)
i have tried a lot but i cannot find why i get an error. If i do it without a loop it works. Any help?
P.S: i use itext 7
I had the below code out of the loop and it should be into the loop...
PdfFont normalFont = PdfFontFactory.createFont(fontDirectory.getAbsolutePath()+"\\arial.ttf", "Identity-H", true);
normal.setFont(normalFont).setFontSize(14);
Style red = new Style();
PdfFont redFont = PdfFontFactory.createFont(fontDirectory.getAbsolutePath()+"\\arial.ttf", "Identity-H", true);
red.setFont(redFont).setFontSize(14).setFontColor(Color.RED);
Style big = new Style();
PdfFont bigFont = PdfFontFactory.createFont(fontDirectory.getAbsolutePath()+"\\arial.ttf", "Identity-H", true);
big.setFont(bigFont).setFontSize(18).setBold();
Related
Using iText7, I'm trying to merge various PDF documents into one single PDF but every printable layer present in the documents ends up being permanently visible.
Is it possible to copy or merge these documents while maintaining the layer properties? It seems as if iText triggers the printable flag, not unlike any "print to PDF" option in any document visualizer.
The first document always has a layer on each page marked as printable that was generated with:
PdfCanvas canvas = new PdfCanvas(page);
PdfLayer printLayer = new PdfLayer("print", pdfDocument);
Canvas canvasModel = new Canvas(canvas, pdfDocument, page.getPageSize());
layerImprimir.setOn(false);
layerImprimir.setOnPanel(false);
layerImprimir.setPrint("Print", true);
canvas.beginLayer(printLayer);
Paragraph paragraph = new Paragraph().setWidth(lineHeight).add(someText);
canvasModel.showTextAligned(paragraph, xPos, yPos, pageNumber, TextAlignment.CENTER, VerticalAlignment.MIDDLE, radAngle);
canvas.endLayer();
canvasModel.close();
Afterwards, that first document is merged with other PDFs that may or may not contain printable layers. I've used both PdfCopy and PdfMerger.
With PdfCopy:
Document finalDocument = new Document();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfCopy copy = new PdfCopy(finalDocument, baos);
PdfReader reader;
finalDocument.open();
reader = new PdfReader(firstDocument);
copy.addDocument(reader);
reader.close();
reader = new PdfReader(secondDocument);
copy.addDocument(reader);
reader.close();
finalDocument.close();
With PdfMerger (from https://stackoverflow.com/a/40594055/13114951):
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfMerger merger = new PdfMerger(pdf);
//Add pages from the first document
PdfDocument firstSourcePdf = new PdfDocument(new PdfReader(SRC1));
merger.merge(firstSourcePdf, 1, firstSourcePdf.getNumberOfPages());
//Add pages from the second pdf document
PdfDocument secondSourcePdf = new PdfDocument(new PdfReader(SRC2));
merger.merge(secondSourcePdf, 1, secondSourcePdf.getNumberOfPages());
firstSourcePdf.close();
secondSourcePdf.close();
pdf.close();
I am using Itext PDF API to generate a pdf. I am trying to get some text to be aligned to the right-hand side of the pdf. I have tried the manual method of spacing but is not working for some reason (Code shown below). Meanwhile, if there is a way of doing it dynamically that would be great, please!
String dest = "\\location\\";
PdfWriter writer;
writer = new PdfWriter(dest);
// Creating a PdfDcoument
PdfDocument pdf = new PdfDocument(writer);
// Creating a Document
Document document = new Document(pdf);
// Creating a String
String para1 = "TEXT";
//Spacing length
while (para1.length() < 50) {
para1 = " " + para1;
}
//Creating Paragraphs
Paragraph paragraph1 = new Paragraph(para1);
//paragraph1.setAlignment(Element.ALIGN_CENTER);
//Adding Paragraphs to document
document.add(paragraph1);
// Closing the document
document.close();
Thanks in advance!
Class com.itextpdf.layout.element.Paragraph in itext7 has method setTextAlignment. I hope this is what you are looking for:
...
paragraph1.setTextAlignment(TextAlignment.RIGHT);
...
I'm using com.itextpdf:itextpdf:5.5.10 and it looks like the stuff has moved around a bit.
paragraph1.setAlignment(com.itextpdf.text.Element.ALIGN_RIGHT)
I need to copy whole AcroForm including field positions and values from template PDF to a new blank PDF file. How can I do that?
In short words - I need to get rid of "background" from the template and leave only filed forms.
The whole point of this is to create a PDF with content that would be printed on pre-printed templates.
I am using IText 5 but I can switch to 7 if usefull examples would be provided
After a lot of trial and error I have found the solution to "How to copy AcfroForm fields into another PDF". It is a iText v7 version. I hope it will help somebody someday.
private byte[] copyFormElements(byte[] sourceTemplate) throws IOException {
PdfReader completeReader = new PdfReader(new ByteArrayInputStream(sourceTemplate));
PdfDocument completeDoc = new PdfDocument(completeReader);
ByteArrayOutputStream out = new ByteArrayOutputStream();
PdfWriter offsetWriter = new PdfWriter(out);
PdfDocument offsetDoc = new PdfDocument(offsetWriter);
offsetDoc.initializeOutlines();
PdfPage blank = offsetDoc.addNewPage();
PdfAcroForm originalForm = PdfAcroForm.getAcroForm(completeDoc, false);
// originalForm.getPdfObject().copyTo(offsetDoc,false);
PdfAcroForm offsetForm = PdfAcroForm.getAcroForm(offsetDoc, true);
for (String name : originalForm.getFormFields().keySet()) {
PdfFormField field = originalForm.getField(name);
PdfDictionary copied = field.getPdfObject().copyTo(offsetDoc, false);
PdfFormField copiedField = PdfFormField.makeFormField(copied, offsetDoc);
offsetForm.addField(copiedField, blank);
}
offsetDoc.close();
completeDoc.close();
return out.toByteArray();
}
Did you check the PdfCopyForms object:
Allows you to add one (or more) existing PDF document(s) to create a new PDF and add the form of another PDF document to this new PDF.
I didn't find an example, but you could try something like this:
PdfReader reader1 = new PdfReader(src1); // a document with a form
PdfReader reader2 = new PdfReader(src2); // a document without a form
PdfCopyForms copy = new PdfCopyForms(new FileOutputStream(dest));
copy.AddDocument(reader1); // add the document without the form
copy.CopyDocumentFields(reader2); // add the fields of the document with the form
copy.close();
reader1.close();
reader2.close();
I see that the class is deprecated. I'm not sure of that's because iText 7 makes it much easier to do this, or if it's because there were technical problems with the class.
This question already has an answer here:
How to update a PDF without creating a new PDF?
(1 answer)
Closed 6 years ago.
I have been trying to add an image to a PDF document using iText 7.
The function I have created to add the image takes a ImageData type and then adds it to a rectangle on a canvas and add that to a PDF. however, I keep getting the error
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
and then
Caused by: java.io.FileNotFoundException: pdf.pdf (The requested operation cannot be performed on a file with a user-mapped section open)
The function code is:
protected void ExportToPdf(ImageData img) throws IOException {
PdfDocument pdfDoc = new PdfDocument(new PdfReader("pdf.pdf"), new PdfWriter("pdf.pdf"));
PdfCanvas canvas = new PdfCanvas(pdfDoc.getFirstPage());
PageSize ps = PageSize.A4;
Rectangle page = new Rectangle(ps.getWidth(),ps.getHeight());
canvas.addImage(img, page, true);
pdfDoc.close();
`
And my main is as follows:
public static void main(String[] args) throws IOException { //adds values to maps for the program to use
//starts PDF writer
PdfWriter writer = new PdfWriter("pdf.pdf");
//Initialize PDF document
PdfDocument pdf = new PdfDocument(writer);
// Initialize document
Document document = new Document(pdf);
pdf.addNewPage();
document.close();
writer.close();
pdf.close();
The full program takes a scene and converts it into an image and then feeds it into the function to be added to the PDF. The code for that is:
WritableImage img = new WritableImage(1000, 700);
scene.snapshot(img);
RenderedImage renderedImage = SwingFXUtils.fromFXImage(img, null);
ImageData imgData = ImageDataFactory.create(SwingFXUtils.fromFXImage(img, null), null);
ExportToPdf(imgData);
Any help would be amazing, thank you.
The problem is already here
PdfDocument pdfDoc = new PdfDocument(new PdfReader("pdf.pdf"), new PdfWriter("pdf.pdf"));
Itext does not support writing to the same file you are reading from. Simply instead write to a temporary file and replace the original file with it when finished.
Using this below Code i am Abel to convert a HTML text To PDF and my code can generate PDF File on particular location . but problem is...... i give font style in body tags so when PDF is generate i am not getting this font style effect in generate PDF ex.
// Here On Body Tag I have given a Zurich BT font style
StyleSheet styles = new StyleSheet();
//styles.loadTagStyle("body", "font-family", "Zurich BT");
styles.loadTagStyle("body", "font", "Zurich BT");
so here my font style is Zurich BT but i have just got plane simple text on generate PDF not get any effect on text.
i am using itextpdf-5.1.1 version and my code is....
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Document pdfDocument = new Document();
Reader htmlreader = new StringReader("<html><head></head><body>"
+ " <font> HELLO MY NAME IS JIMIT TANK </font> </html></body>");
PdfWriter.getInstance(pdfDocument, baos);
pdfDocument.open();
// Here On Body Tag I am giving a Zurich BT font style
StyleSheet styles = new StyleSheet();
//styles.loadTagStyle("body", "font-family", "Zurich BT");
styles.loadTagStyle("body", "font", "Zurich BT");
ArrayList arrayElementList = HTMLWorker.parseToList(htmlreader,styles);
for (int i = 0; i < arrayElementList.size(); ++i) {
Element e = (Element) arrayElementList.get(i);
pdfDocument.add(e);
}
pdfDocument.close();
byte[] bs = baos.toByteArray();
String pdfBase64 = Base64.encodeBytes(bs); //output
File pdfFile = new File("c:/pdfExample.pdf");
FileOutputStream out = new FileOutputStream(pdfFile);
out.write(bs);
out.close();
Use iTextSharp Paragraph class and set font and style to it like this
Document doc = new Document(PageSize.A4);
Paragraph paraReportTitle = new Paragraph();
//paraReportTitle.Font = new Font(Font.FontFamily.HELVETICA, 13f, Font.BOLD);
paraReportTitle.Font = new Font(Font.FontFamily.HELVETICA, 8f, Font.NORMAL);
doc.Add(paraReportTitle);
Setting style to html will not work.
You can also use the BaseFont class in iTextSharp