When I generate a pdf document with Link API, there have some strange things. A rectangle always outside the link text. It looks like the cell rectangle, but I didn't set any cell in the document.
My code is like this:
try (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(file));
Document document = new Document(pdfDocument);) {
PdfAction pdfAction = PdfAction.createURI("https://kb.itextpdf.com/home");
Link link = new Link("https://kb.itextpdf.com/home", pdfAction);
Paragraph paragraph = new Paragraph();
paragraph.add(link);
document.add(paragraph);
} catch (Exception e) {
System.out.println(e);
}
I resolved it like this:
PdfLinkAnnotation linkAnnotation = link.getLinkAnnotation();
linkAnnotation.setBorder(new PdfAnnotationBorder(0, 0, 0));
Related
How to add an external link in PDF and redirect to the webpage.
.
.
.
example image describe below
On click on Goolge,user should redirect to webpage https://www.google.com
here is my code
private void createPDFiText() {
int margin = getResources().getDimensionPixelSize(R.dimen._5sdp);
Document document = new Document(PageSize.A4, margin, margin, margin, margin);
try {
PdfWriter.getInstance(document, getOutputStream());
document.open();
for (int i = 12; i <= 17; i++) {
Phrase phrase = new Phrase("Open ");
Phrase phrase1 = new Phrase(" on Click On it.");
Font anchorFont = new Font(Font.FontFamily.UNDEFINED, 25);
anchorFont.setColor(BaseColor.BLUE);
anchorFont.setStyle(Font.FontStyle.UNDERLINE.getValue());
Anchor anchor = new Anchor("Google", anchorFont);
anchor.setReference("www.google.com");
phrase.add(anchor);
phrase.add(phrase1);
document.add(phrase);
}
document.close();
} catch (DocumentException | IOException e) {
e.printStackTrace();
}
}
I am referring to this answer. Have a look. Modifying existing pdf file using iText 5.5.13.2 is complicated. But the referred solution is more easier.
iText 7 has handier way to modify existing pdf.
There are several other ways. Like PdfStamper etc.
From referred answer, add following code to make an anchor.
Phrase phrase = new Phrase("Open ");
Phrase phrase1 = new Phrase(" on Click On it.");
Font anchorFont = new Font(Font.FontFamily.UNDEFINED, 11);
anchorFont.setColor(BaseColor.BLUE);
anchorFont.setStyle(Font.FontStyle.UNDERLINE.getValue());
Anchor anchor = new Anchor("Google", anchorFont);
anchor.setReference("www.google.com");
phrase.add(anchor);
phrase.add(phrase1);
document.add(phrase);
Change the font and colors based on your needs.
Full code:
try {
PdfReader reader = new PdfReader("test.pdf"); //src pdf path (the pdf I need to modify)
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("test2.pdf")); // destination pdf path
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfImportedPage page = writer.getImportedPage(reader, 1);
document.newPage();
document.setPageSize(reader.getPageSize(1));
cb.addTemplate(page, 0, 0);
Phrase phrase = new Phrase("Open ");
Phrase phrase1 = new Phrase(" on Click On it.");
Font anchorFont = new Font(Font.FontFamily.UNDEFINED, 11);
anchorFont.setColor(BaseColor.BLUE);
anchorFont.setStyle(Font.FontStyle.UNDERLINE.getValue());
Anchor anchor = new Anchor("Google", anchorFont);
anchor.setReference("https://www.google.com");
phrase.add(anchor);
phrase.add(phrase1);
document.add(phrase);
document.close();
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
I am having html content store as a raw string in my database and I like to print it in pdf, but with custom size, for example page size to be 10cm width and 7 com height, not standard A4 format.
Can someone gives me some examples if it is possible.
ByteArrayOutputStream out = new ByteArrayOutputStream();
PDRectangle rec = new PDRectangle(recWidth, recHeight);
PDPage page = new PDPage(rec);
try (PDDocument document = new PDDocument()) {
PdfRendererBuilder builder = new PdfRendererBuilder();
builder.defaultTextDirection(BaseRendererBuilder.TextDirection.LTR);
String htmlContent = "<b>Hello world</b>" + content;
builder.withHtmlContent(htmlContent, "");
document.addPage(page);
builder.usePDDocument(document);
PdfBoxRenderer renderer = builder.buildPdfRenderer();
renderer.createPDFWithoutClosing();
document.save(out);
} catch (Exception e) {
ex.printStackTrace();
}
return new ByteArrayInputStream(out.toByteArray());
This code generates for me 2 files, one small and one A4.
UPDATE:
I tried this one:
try (PDDocument document = new PDDocument()) {
PdfRendererBuilder builder = new PdfRendererBuilder();
builder.defaultTextDirection(BaseRendererBuilder.TextDirection.LTR);
builder.useDefaultPageSize(210, 297, PdfRendererBuilder.PageSizeUnits.MM);
builder.usePdfAConformance(PdfRendererBuilder.PdfAConformance.PDFA_3_A);
String htmlContent = "<b>content</b>";
builder.withHtmlContent(htmlContent, "");
builder.usePDDocument(document);
PdfBoxRenderer renderer = builder.buildPdfRenderer();
renderer.createPDFWithoutClosing();
document.save(out);
} catch (Exception e) {
log.error(">>> The creation of PDF is invalid!");
}
But in this case content is not shown, if I remove useDefaultPageSize, content will be shown
I didn't check this solution before, but try initialise the builder object with your desired page size and document type like below
builder.useDefaultPageSize(210, 297, PdfRendererBuilder.PageSizeUnits.MM);
builder.usePdfAConformance(PdfRendererBuilder.PdfAConformance.PDFA_3_A);
the lib include many PDF format next is PdfAConformance Enum with possible values
PdfAConformance Enum
I would like to add a top level bookmark to an existing pdf file using PDFBOX in JAVA.
Not sure why the following code was not working, can anyone help me out? Thanks.
Below is how the Document.pdf looks like in the bookmark section.
Top
---Node-1
-------Node-11
-------Node-12
....
---Node-2
-------Node-21
....
Java code (Part within the program) :
PDDocument document = PDDocument.load(new File("C:/Users/Desktop/document.pdf"))
PDDocumentOutline documentOutline = new PDDocumentOutline();
document.getDocumentCatalog().setDocumentOutline(documentOutline);
PDOutlineItem pagesOutline = new PDOutlineItem();
pagesOutline.setTitle("All Pages");
documentOutline.addFirst(pagesOutline);
pagesOutline.openNode();
documentOutline.openNode();
document.getDocumentCatalog().setPageMode(PageMode.USE_OUTLINES);
document.save("C:/Users/Desktop/document.pdf");
document.close()
Here's my attempt at this, I'm keeping my filename if asked questions later.
What I did is to wrap the old outline into a new item. It is not possible to add the existing items one by one, because only "orphans" can be added.
PDDocument document = PDDocument.load(new File("000009.pdf"));
PDDocumentOutline oldDocumentOutline = document.getDocumentCatalog().getDocumentOutline();
PDDocumentOutline documentOutline = new PDDocumentOutline();
document.getDocumentCatalog().setDocumentOutline(documentOutline);
PDOutlineItem pagesOutline = new PDOutlineItem();
//pagesOutline.setTitle("All Pages");
//documentOutline.addFirst(pagesOutline);
PDOutlineItem oldOutlineItemWrapped = new PDOutlineItem(oldDocumentOutline.getCOSObject());
oldOutlineItemWrapped.setTitle("All Pages");
documentOutline.addFirst(oldOutlineItemWrapped);
//pagesOutline.openNode();
oldOutlineItemWrapped.openNode();
documentOutline.openNode();
document.getDocumentCatalog().setPageMode(PageMode.USE_OUTLINES);
document.save("000009-modified.pdf");
document.close();
I want to add an image which is retrieved from the mysql db and print it on a pdf file in iText java. The image retrieved from the db is stored in the lblimg. How do I achieve that in java ?
Here's my partial code:
String filename = null;
int s = 0;
byte[] person_img = null;
uploadbtn = new JButton("Upload a Photo");
uploadbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filename = f.getAbsolutePath();
try{
File img = new File(filename);
FileInputStream fis = new FileInputStream(img);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
for(int readNum; (readNum = fis.read(buf)) != -1;){
bos.write(buf, 0, readNum);
}
person_img = bos.toByteArray();
fis.close();
}catch(Exception e1){
e1.printStackTrace();
}
}
});
// Partial code for adding image to db
stt.setBytes(8, person_img);
// Partial codes for retrieving image from db
byte[] imageData = rs.getBytes("Image");
format = new ImageIcon(imageData);
lblimg.setIcon(format);
//Creating the document and adding the lblimg (which contains the image retrieved from the db). PLEASE HELP HERE. I CANNOT ADD THE IMAGE TO PDF document.
Document doc = new Document();
PdfWriter.getInstance(doc, new FileOutputStream("Report.pdf"));
doc.open();
doc.add(new Paragraph( // img to be added here ));
Update 1 by Bruno Lowagie
Snippet taken from the full code:
try {
Image i = Image.getInstance((PdfTemplate) lblimg.getIcon());
Document doc = new Document();
PdfWriter.getInstance(doc, new FileOutputStream("Report.pdf"));
doc.open();
Image img = Image.getInstance("ja.png");
doc.add(img);
doc.add(i);
doc.add(new Paragraph("Employee Information", FontFactory.getFont(FontFactory.TIMES_BOLD,18, Font.BOLD, BaseColor.RED)));
doc.add(new Paragraph("______________________________________________________________________________"));
doc.add(new Paragraph("Employee ID is " + val1));
doc.add(new Paragraph("First Name is " + val2 + "\t\t" + " Last Name is " + val3));
doc.add(new Paragraph("Job Position " + val4));
doc.add(new Paragraph("Allowances allowed " + val5));
doc.add(new Paragraph("Salary " + val10));
JOptionPane.showMessageDialog(null, "Report Saved");
doc.close();
} catch(Exception e1) {
e1.printStackTrace();
}
As getIcon returns a javax.swing class and as PdfTemplate is an iText class extending the PdfContentByte class that contains a ByteBuffer of PDF syntax, a ClassCastException is thrown here: (PdfTemplate) lblimg.getIcon()
Update 2 by Bruno Lowagie
The actual question was posted as a comment: How do I retrieve an image which is in a JLabel and add it on a PDF? This question is answered in update 3 of my answer.
Assuming that this contains an image:
byte[] imageData = rs.getBytes("Image");
In other words: assuming that imageData is a valid JPEG, JPEG2000, GIF, PNG, BMP, WMF, TIFF or JBIG2 image, then you can create a com.itextpdf.text.Image object like this:
Image img = Image.getInstance(imageData);
Once you have this img instance, you can add it to the document like this:
document.add(img);
I don't understand why you'd create an ImageIcon instance. Nor is it clear why you refer to a Paragraph object.
Update 1:
Now that I see your full code, I see a very strange line:
Image i = Image.getInstance((PdfTemplate) lblimg.getIcon());
You are casting a javax.swing object to an iText object. This can never work. You should get a ClassCastException at this point in your code.
I also see that you know how to add an image from a file:
Image img = Image.getInstance("ja.png");
doc.add(img);
When you don't have a path to a file, the fastest way you'll find alternative getInstance() methods, is by consulting the Javadoc API documentation: http://api.itextpdf.com/itext/com/itextpdf/text/Image.html#getInstance(byte[])
Update 2:
I have updated the question so that it contains the relevant code. As explained in my answer (that unfortunately wasn't accepted), the following line throws a ClassCastException:
Image i = Image.getInstance((PdfTemplate) lblimg.getIcon());
This exception is caught like this:
} catch(Exception e1) {
e1.printStackTrace();
}
Hence all the code starting with the following line is skipped:
Document doc = new Document();
As a result, no document is created. This is not an iText problem. This is a case of bad exception handling.
Update 3:
Finally, the real question is asked in a comment: In simple words: How to I retrieve an image which is in a JLabel and add it on a PDF?
Again it turns out that I have already answered that question. I referred to the Javadoc API documentation for the Image class. We find the following getInstance() method: http://api.itextpdf.com/itext/com/itextpdf/text/Image.html#getInstance(java.awt.Image, java.awt.Color)
In other words, we can create an iText Image object using a Java Image object. You have the following line in your code:
ImageIcon format = new ImageIcon(imageData);
Or, in your case, you could try something like:
ImageIcon format = (ImageIcon)lblimg.getIcon();
You can get a java.awt.Image object from this ImageIcon like this:
java.awt.Image awtImage = format.getImage();
As per the iText API documentation, you can create an iText image like this:
Image img = Image.getInstance(awtImage, null);
How do i add an image on the last page of existing PDF document. Please help me.
The following example adds an image to the second page of an existing pdf using Itext 5.
String src = "c:/in.pdf;
String dest = "c:/out.pdf";
String IMG = "C:/image.jpg";
try {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
com.itextpdf.text.Image image = com.itextpdf.text.Image.getInstance(IMG);
image.setAbsolutePosition(36, 400);
PdfContentByte over = stamper.getOverContent(2);
over.addImage(image);
stamper.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
You can read the text from the PDF using the same ITEXT library.Try this
PdfReader reader = new PdfReader(INPUTFILE);
int n = reader.getNumberOfPages();
PdfTextExtractor parser =new PdfTextExtractor(new PdfReader("C:/Text.pdf"));
parser.getTextFromPage(3); // Extracting the content from a particular page.
After you have add your data ,You can load images either from file or from a URL, like this:
Image image1 = Image.getInstance("watermark.png");
document.add(image1);
String imageUrl = "http://applause-voice.com/wp-content/uploads/2011/04/1hello.jpg";
Image image2 = Image.getInstance(new URL(imageUrl));
document.add(image2);
If you will add this code at the end of your Java Program , then the image will automatically comes at the end of your page.
The best solution for me was to create a new in-memory PDF document with the image I want to add, then copy this page to the original document.
// Create a separate doc for image
var pdfDocWithImageOutStream = new ByteArrayOutputStream();
var pdfDocWithImage = new PdfDocument(new PdfWriter(pdfDocWithImageOutStream).setSmartMode(true));
var docWithImage = new Document(pdfDocWithImage, destinationPdf.getDefaultPageSize());
// Add image to the doc
docWithImage.add(image);
// Close the doc to save data
docWithImage.close();
pdfDocWithImage.close();
// Open the same doc for reading
pdfDocWithImage = new PdfDocument(new PdfReader(new ByteArrayInputStream(pdfDocWithImageOutStream.toByteArray())));
docWithImage = new Document(pdfDocWithImage, destinationPdf.getDefaultPageSize());
// Copy page to original (destinationPdf)
pdfDocWithImage.copyPagesTo(1, pdfDocWithImage.getNumberOfPages(), destinationPdf);
docWithImage.close();
pdfDocWithImage.close();