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've been trying to compose a pie chart using XChart then vectorising it to SVG format to use it in a PDF built with PDFBox.
To do that, I use:
XChart for the pie chart building and vectorising it ;
SVGSalamender for the Graphics2D building based on previous SVG vectorising ;
PDFBoxGraphics2D for adding previous Graphics2D to my PDF.
Everything runs fine (in compiles and runs without errors) but it does not work. The output PDF stays empty.
This is my code:
#Test
public void test() {
try {
PieChart camembertXChart = camembertXChart();
BufferedImage imageCamembertXChart = BitmapEncoder.getBufferedImage(camembertXChart);
ByteArrayOutputStream output = new ByteArrayOutputStream();
File svg = new File("F:\\Users\\mangin\\Desktop\\Camembert_XChart.svg");
VectorGraphicsEncoder.saveVectorGraphic(camembertXChart, svg.getName(), VectorGraphicsFormat.SVG);
byte[] data = output.toByteArray();
FileInputStream input = new FileInputStream(svg);
BufferedImage imageCamembertXChartVectorise = ImageIO.read(input);
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
PDPageContentStream contenu = new PDPageContentStream(document, page, AppendMode.APPEND, false, true);
PdfBoxGraphics2D pdfBoxGraphics2D = new PdfBoxGraphics2D(document, 200, 200);
// SVG Salamander
SVGUniverse universSVG = new SVGUniverse();
SVGDiagram diagramSVG = universSVG.getDiagram(universSVG.loadSVG(svg.toURI().toURL()));
diagramSVG.render(pdfBoxGraphics2D);
pdfBoxGraphics2D.dispose();
var xform = pdfBoxGraphics2D.getXFormObject();
var transform = AffineTransform.getTranslateInstance(200, 200);
xform.setMatrix(transform);
contenu.drawForm(xform);
contenu.close();
document.save("D://tests/archi/PDF_avec_elements_graphique.pdf");
document.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private PieChart camembertXChart() {
PieChart camembert2 = new PieChartBuilder().width(200).height(200).build();
Color[] sliceColors = new Color[] {
new Color(183, 203, 231),
new Color(131, 173, 219),
new Color(84, 143, 197),
new Color(70, 120, 165) };
camembert2.getStyler().setSeriesColors(sliceColors);
camembert2.getStyler().setLegendVisible(false);
camembert2.getStyler().setPlotBorderVisible(false);
camembert2.getStyler().setChartTitleVisible(false);
camembert2.getStyler().setChartTitleBoxVisible(false);
camembert2.getStyler().setChartPadding(0);
camembert2.getStyler().setChartTitlePadding(0);
camembert2.getStyler().setBorderWidth(3);
camembert2.getStyler().setAnnotationsFont(new Font("Arial", Font.BOLD, 10));
camembert2.getStyler().setAnnotationsFontColor(Color.WHITE);
camembert2.addSeries("Item 1", 9);
camembert2.addSeries("Item 2", 10);
camembert2.addSeries("Item 3", 23);
camembert2.addSeries("Item 4", 58);
return camembert2;
}
Does anyone have any experience in an equivalent development ? Or does anybody know why the PDF is empty?
Thanks and regards,
Thomas.
I created a PDF file in Java using OpenPDF and inserted a paragraph. The problem is that I want to place it in the middle, not on the left. How can this be done?
Second question: How can I place a word with specific formatting in the test?
For example: "Hello and welcome" (welcome should be bold)
This is my code:
Document document = new Document();
String PDFPath = "output.pdf";
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(PDFPath));
Font font_bold = new Font(Font.TIMES_ROMAN, 16, Font.BOLD, Color.BLACK);
Font font_normal = new Font(Font.TIMES_ROMAN, 15, Font.NORMAL, Color.BLACK);
Paragraph p1 = new Paragraph("Ordonnance", font_bold);
document.open();
document.add(p1);
document.close();
You need to define the alignment if you want to have the paragraph centred:
p1.setAlignment(Element.ALIGN_CENTER);
To apply formatting to some parts of the text, you can divide it into several chunks. A Chunk in OpenPDF is a string with a certain Font. Instead of adding a String (unformatted) to the paragraph, you add a Chunk-object like new Chunk("Hello and ", fontNormal) which defines the text and the font to be used.
Here is the code for what you want to do according to the question:
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("output.pdf"));
document.open();
Font fontNormal = new Font(Font.TIMES_ROMAN, 15, Font.NORMAL);
Font fontBold = new Font(Font.TIMES_ROMAN, 16, Font.BOLD);
Paragraph p1 = new Paragraph();
p1.setAlignment(Element.ALIGN_CENTER);
p1.add(new Chunk("Hello and ", fontNormal));
p1.add(new Chunk("welcome", fontBold));
document.add(p1);
document.close();
The result looks like this:
Your first line had some weird declaration, but this should work:
Document document = new Document();
String PDFPath = "D:\\test.pdf";
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(PDFPath));
Font font_bold = new Font(Font.TIMES_ROMAN, 16, Font.BOLD, Color.BLACK);
Font font_normal = new Font(Font.TIMES_ROMAN, 15, Font.NORMAL, Color.BLACK);
Paragraph p1 = new Paragraph("Ordonnance", font_bold);
p1.setAlignment(Element.ALIGN_CENTER);
document.open();
document.add(p1);
document.close();
You just have to set the alignment of the paragraph
I would like to add a link in my overlay text. I've read that using Anchor will only work for documents made from scratch but not for existing pdfs. My code is adding an overlay text to every page. My goal is to make a portion of that text clickable. I don't know how to make a link annotation that is part of a phrase.
Here's my code:
int n = reader.getNumberOfPages();
// step 4: we add content
PdfImportedPage page;
PdfCopy.PageStamp stamp;
for (int j = 0; j < n; )
{
++j;
page = writer.getImportedPage(reader, j);
if (i == 1) {
stamp = writer.createPageStamp(page);
Rectangle mediabox = reader.getPageSize(j);
Rectangle crop = new Rectangle(mediabox);
writer.setCropBoxSize(crop);
// add overlay text
Paragraph p = new Paragraph();
p.setAlignment(Element.ALIGN_CENTER);
FONT_URL_OVERLAY.setColor(0, 191, 255);
// get current user
EPerson loggedin = context.getCurrentUser();
String eperson = null;
if (loggedin != null)
{
eperson = loggedin.getFullName();
}
else eperson = "Anonymous";
Phrase downloaded = new Phrase();
Chunk site = new Chunk("My Website",FONT_URL_OVERLAY);
site.setAction(new PdfAction("http://www.mywebsite.com"));
downloaded.add(new Chunk("Downloaded by [" + eperson + "] from ", FONT_OVERLAY));
downloaded.add(site);
downloaded.add(new Chunk(" on ", FONT_OVERLAY));
downloaded.add(new Chunk(new SimpleDateFormat("MMMM d, yyyy").format(new Date()), FONT_OVERLAY));
downloaded.add(new Chunk(" at ", FONT_OVERLAY));
downloaded.add(new Chunk(new SimpleDateFormat("h:mm a z").format(new Date()), FONT_OVERLAY));
p.add(downloaded);
ColumnText.showTextAligned(stamp.getOverContent(), Element.ALIGN_CENTER, p,
crop.getLeft(10), crop.getHeight() / 2 + crop.getBottom(), 90);
stamp.alterContents();
}
writer.addPage(page);
}
So my overlay would looked like this:
Downloaded by [Anonymous] from My Website on February 17, 2015 at 1:20 AM CST
How can I convert My Website to a link annotation? Searching here in SO, I found this post, but I don't know how to apply adding link annotation to a portion of my overlay text.
Thanks in advance.
EDIT: How to add a rotated overlay text with link annotations to existing pdf?
Thanks to Bruno Lowagie for going out of his way in answering my question. Although I originally asked how to add link annotations in an overlay text to existing pdfs, he also catered my questions in the comments section of his answer about setting the coordinates properly if the overlay text were rotated.
You are using ColumnText.showAligned() which is sufficient to add a line of text without any special features, but if you want the anchor to work, you need to use ColumnText differently.
This is shown in the AddLinkAnnotation2 example:
public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
PdfContentByte canvas = stamper.getOverContent(1);
Font bold = new Font(FontFamily.HELVETICA, 12, Font.BOLD);
Chunk chunk = new Chunk("The Best iText Questions on StackOverflow", bold);
chunk.setAnchor("http://pages.itextpdf.com/ebook-stackoverflow-questions.html");
Phrase p = new Phrase("Download ");
p.add(chunk);
p.add(" and discover more than 200 questions and answers.");
ColumnText ct = new ColumnText(canvas);
ct.setSimpleColumn(36, 700, 559, 750);
ct.addText(p);
ct.go();
stamper.close();
reader.close();
}
In this case, we define a rectangle for a ColumnText object, we add the Phrase to the column, and we go().
If you check the result, link_annotation2.pdf, you'll notice that you can click the words in bold.
There are no plans to support this in ColumnText.showTextAligned(). That is a convenience method that can be used as a short-cut for the handful of lines shown above, but there are some known limitations: lines are not wrapped, interactivity is ignored,...
Update 1: in the comment section, you asked an additional question about rotation the content and the link.
Rotating the content isn't difficult. There's even more than one way to do that. Rotating the link isn't trivial, as a link is a type of annotation, and annotations aren't part of the content.
Let's first take a look at AddLinkAnnotation3:
public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
AffineTransform transform = AffineTransform.getRotateInstance(Math.PI / 6);
stamper.getWriter().setPageEvent(new AddAnnotation(stamper, transform));
PdfContentByte canvas = stamper.getOverContent(1);
Font bold = new Font(FontFamily.HELVETICA, 12, Font.BOLD);
Chunk chunk = new Chunk("The Best iText Questions on StackOverflow", bold);
chunk.setGenericTag("http://pages.itextpdf.com/ebook-stackoverflow-questions.html");
Phrase p = new Phrase("Download ");
p.add(chunk);
p.add(" and discover more than 200 questions and answers.");
canvas.saveState();
canvas.concatCTM(transform);
ColumnText ct = new ColumnText(canvas);
ct.setSimpleColumn(300, 0, 800, 400);
ct.addText(p);
ct.go();
canvas.restoreState();
stamper.close();
reader.close();
}
In this example, we define a tranformation of 30 degrees (Math.PI / 6):
AffineTransform transform = AffineTransform.getRotateInstance(Math.PI / 6);
We use this transformation when rendering the column:
canvas.saveState();
canvas.concatCTM(transform);
// render column
canvas.restoreState();
This rotates the content, but we didn't add any annotation yet. Instead, we define a page event:
stamper.getWriter().setPageEvent(new AddAnnotation(stamper, transform));
and we introduced a generic tag:
chunk.setGenericTag("http://pages.itextpdf.com/ebook-stackoverflow-questions.html");
To add the annotation, we use some magic in the page event implementation:
public class AddAnnotation extends PdfPageEventHelper {
protected PdfStamper stamper;
protected AffineTransform transform;
public AddAnnotation(PdfStamper stamper, AffineTransform transform) {
this.stamper = stamper;
this.transform = transform;
}
#Override
public void onGenericTag(PdfWriter writer, Document document, Rectangle rect, String text) {
float[] pts = {rect.getLeft(), rect.getBottom(), rect.getRight(), rect.getTop()};
transform.transform(pts, 0, pts, 0, 2);
float[] dstPts = {pts[0], pts[1], pts[2], pts[3]};
rect = new Rectangle(dstPts[0], dstPts[1], dstPts[2], dstPts[3]);
PdfAnnotation annot = PdfAnnotation.createLink(writer, rect, PdfAnnotation.HIGHLIGHT_INVERT, new PdfAction(text));
stamper.addAnnotation(annot, 1);
}
}
We create an annotation, but before we do so, we perform a transformation on the rectangle. This makes sure that the text fits the rectangle with the text that needs to be clickable, but... this may not be what you expect:
You may have wanted the rectangle to be rotated, and that's possible, but it's more math. For instance: you could create a polygon that is a better fit: ITextShape Clickable Polygon or path
Fortunately, you don't need an angle of 30 degrees, you want to rotate the text with an angle of 90 degrees. In that case, you don't have the strange effect shown in the above screen shot.
Take a look at AddLinkAnnotation4
public class AddAnnotation extends PdfPageEventHelper {
protected PdfStamper stamper;
protected AffineTransform transform;
public AddAnnotation(PdfStamper stamper, AffineTransform transform) {
this.stamper = stamper;
this.transform = transform;
}
#Override
public void onGenericTag(PdfWriter writer, Document document, Rectangle rect, String text) {
float[] pts = {rect.getLeft(), rect.getBottom(), rect.getRight(), rect.getTop()};
transform.transform(pts, 0, pts, 0, 2);
float[] dstPts = {pts[0], pts[1], pts[2], pts[3]};
rect = new Rectangle(dstPts[0], dstPts[1], dstPts[2], dstPts[3]);
PdfAnnotation annot = PdfAnnotation.createLink(writer, rect, PdfAnnotation.HIGHLIGHT_INVERT, new PdfAction(text));
annot.setBorder(new PdfBorderArray(0, 0, 0));
stamper.addAnnotation(annot, 1);
}
}
As you can see, I've added a single line to remove the border (the border is there by default unless you redefine the PdfBorderArray).
The rest of the code is also almost identical. We now define an angle of Math.PI / 2 (90 degrees).
public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
AffineTransform transform = AffineTransform.getRotateInstance(Math.PI / 2);
stamper.getWriter().setPageEvent(new AddAnnotation(stamper, transform));
PdfContentByte canvas = stamper.getOverContent(1);
Font bold = new Font(FontFamily.HELVETICA, 12, Font.BOLD);
Chunk chunk = new Chunk("The Best iText Questions on StackOverflow", bold);
chunk.setGenericTag("http://pages.itextpdf.com/ebook-stackoverflow-questions.html");
Phrase p = new Phrase("Download ");
p.add(chunk);
p.add(" and discover more than 200 questions and answers.");
canvas.saveState();
canvas.concatCTM(transform);
ColumnText ct = new ColumnText(canvas);
ct.setSimpleColumn(36, -559, 806, -36);
ct.addText(p);
ct.go();
canvas.restoreState();
stamper.close();
reader.close();
}
Note that the lower left corner of the page is the pivot point, hence we need to adapt the coordinates where we add the column, otherwise you'll rotate all the content outside the visible area of the page.
Update 2:
In yet another comment, you are asking about the coordinates you need to use when adding text in a rotated coordinate system.
I made this drawing:
In the top part, you add the word MIDDLE in the middle of a page, but that's not where it will appear: you are rotating everything by 90 degrees, hence the word MIDDLE will rotate outside your page (into the hatched area). The word will be in the PDF, but you'll never see it.
If you look at my code, you see that I use these coordinates:
ct.setSimpleColumn(36, -559, 806, -36);
This is outside the visible area (it's below the actual page dimensions), but as I rotate everything with 90 degrees, it rotates into the visible area.
If you look at my drawing, you can see that the page with coordinates (0, 0), (0, -595), (842, -598) and (842, 0) rotates by 90 degrees and thus gets the coincides with a page with coordinates (0, 0), (595, 0), (595, 842) and (0, 842). That's the type of Math we all learned in high school ;-)
You were adding text at position crop.getLeft(10), crop.getHeight() / 2 + crop.getBottom(). If you know that the text will be rotated by 90 degrees, you should use crop.getHeight() / 2 + crop.getBottom(), -crop.getLeft().
The best way to understand why, is to make a drawing.
I have the following code :
PdfReader reader = new PdfReader("doc.pdf");
PdfStamper stamper = new PdfStamper(reader,
new FileOutputStream("AttestationTemp.pdf"));
PdfContentByte over = stamper.getOverContent(1);
BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1257, false);
over.setFontAndSize(bf, 50);
over.beginText();
ColumnText.showTextAligned(over, Element.ALIGN_LEFT, new Phrase("String"), 110, 384, 0);
over.endText();
try
{
if (Desktop.isDesktopSupported())
{
File myPDF = new File("doc.pdf");
Desktop.getDesktop().open(myPDF);
}
}
catch (Exception e)
{
e.printStackTrace();
}
The problem is that when I change the size of my String using the setFontAndSize method, I get the same result (same small size), so I want to know how to set the size of the string added to the pdf file.
iText offers APIs for PDF content generation at different levels.
There is a very low level API of PdfContentByte methods. At this level you manually add individual content stream operations one-by-one, e.g.:
PdfContentByte over = ...;
over.setFontAndSize(bf, 50);
over.beginText();
over.setTextMatrix(110, 384);
over.showText("Hello World!");
over.endText();
Then there is the higher level API of ColumnText methods. At this level you construct and style your text using Phrase and Chunk objects and the ColumnText methods create the corresponding content stream operations:
PdfContentByte over = ...;
Phrase phrase = new Phrase("Hello World!", new Font(bf, 50));
ColumnText.showTextAligned(over, Element.ALIGN_LEFT, phrase, 110, 384, 0);
The code of the OP mixes instructions at these levels which in his case results in his font setting call to later be overridden and, therefore, ignored.