sizing a String added to a pdf file using itext - java

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.

Related

Creating a PDF/A-3 with form fields using iText 7 results in PdfAConformanceException

I want to use iText 7 (7.0.7 actually) to create a PDF/A-3 file with form fields.
I checked the examples and the jump tutorial to do so.
After adding a form field to here
like shown here, I get the following error:
Exception in thread "main" com.itextpdf.pdfa.PdfAConformanceException: An annotation dictionary shall contain the f key
at com.itextpdf.pdfa.checker.PdfA2Checker.checkAnnotation(PdfA2Checker.java:336)
at com.itextpdf.pdfa.checker.PdfAChecker.checkAnnotations(PdfAChecker.java:467)
at com.itextpdf.pdfa.checker.PdfAChecker.checkPage(PdfAChecker.java:446)
at com.itextpdf.pdfa.checker.PdfAChecker.checkPages(PdfAChecker.java:434)
at com.itextpdf.pdfa.checker.PdfAChecker.checkDocument(PdfAChecker.java:182)
at com.itextpdf.pdfa.PdfADocument.checkIsoConformance(PdfADocument.java:296)
at com.itextpdf.kernel.pdf.PdfDocument.close(PdfDocument.java:742)
at com.itextpdf.layout.Document.close(Document.java:120)
at pdfatest.C07E03_UnitedStates_PDFA_3a.createPdf(C07E03_UnitedStates_PDFA_3a.java:158)
at pdfatest.C07E03_UnitedStates_PDFA_3a.main(C07E03_UnitedStates_PDFA_3a.java:40)
This is the modified example code:
public void createPdf(String dest) throws IOException {
PdfADocument pdf = new PdfADocument(new PdfWriter(dest),
PdfAConformanceLevel.PDF_A_3A,
new PdfOutputIntent("Custom", "", "http://www.color.org",
"sRGB IEC61966-2.1", new FileInputStream(INTENT)));
Document document = new Document(pdf, PageSize.A4.rotate());
document.setMargins(20, 20, 20, 20);
//Setting some required parameters
pdf.setTagged();
pdf.getCatalog().setLang(new PdfString("en-US"));
pdf.getCatalog().setViewerPreferences(
new PdfViewerPreferences().setDisplayDocTitle(true));
PdfDocumentInfo info = pdf.getDocumentInfo();
info.setTitle("iText7 PDF/A-3 example");
//Add attachment
PdfDictionary parameters = new PdfDictionary();
parameters.put(PdfName.ModDate, new PdfDate().getPdfObject());
PdfFileSpec fileSpec = PdfFileSpec.createEmbeddedFileSpec(
pdf, Files.readAllBytes(Paths.get(DATA)), "united_states.csv",
"united_states.csv", new PdfName("text/csv"), parameters,
PdfName.Data, false);
fileSpec.put(new PdfName("AFRelationship"), new PdfName("Data"));
pdf.addFileAttachment("united_states.csv", fileSpec);
PdfArray array = new PdfArray();
array.add(fileSpec.getPdfObject().getIndirectReference());
pdf.getCatalog().put(new PdfName("AF"), array);
//Embed fonts
PdfFont font = PdfFontFactory.createFont(FONT, true);
PdfFont bold = PdfFontFactory.createFont(BOLD_FONT, true);
// Create content
Table table = new Table(new float[]{4, 1, 3, 4, 3, 3, 3, 3, 1});
table.setWidthPercent(100);
BufferedReader br = new BufferedReader(new FileReader(DATA));
String line = br.readLine();
process(table, line, bold, true);
while ((line = br.readLine()) != null) {
process(table, line, font, false);
}
br.close();
document.add(table);
// START additional code to add a form field
PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);
PdfFormField textFormField = PdfFormField.createText(
pdf,
new Rectangle(50, 50, 200, 15),
"vo-1-text", "bla", font, 12.0f);
form.addField(textFormField);
// END additional code to add a form field
//Close document
document.close();
}
Am I missing something?
If you can switch to iText 7.1.x, then it's relatively easy: there is a new overload for createText which allows you to set aPdfAConformanceLevel parameter, so
PdfFormField textFormField = PdfFormField.createText(
pdf,
new Rectangle(50, 50, 200, 15),
"vo-1-text", "bla", font, 12.0f,
false, // multiline parameter
PdfAConformanceLevel.PDF_A_3A // <-- this is the important one
);
If you can't, or won't, switch to iText 7.1, then you can try manually triggering the code that will set the flag:
for (PdfWidgetAnnotation wid : textFormField.getWidgets()) {
wid.setFlag(PdfAnnotation.PRINT);
}
I'm not sure if this last approach will work, because you may need to have explicitly defined the PdfWidgetAnnotation, but it is much easier to go to iText 7.1.

IText Stamper undeline specific text

I'm trying to do a report from a java swing application, I tried jasper reports and other tools, but I don't understand how to use them properly.
I gave a try to itext, and I actually have something like this.
public void createPDF(){
try {
PdfReader reader = new PdfReader("pdf/watermark.pdf"); // input PDF
PdfStamper stamper = new PdfStamper(reader,new FileOutputStream("C:\\Users\\FIREFENIX\\Documents\\NetBeansProjects\\Java\\PDFCreator\\src\\pdf\\watermarkFinal.pdf")); // output PDF
BaseFont bfArialPlain = BaseFont.createFont("/font/arial.ttf",BaseFont.IDENTITY_H,BaseFont.EMBEDDED);
BaseFont bfArialBold = BaseFont.createFont("/font/arialbd.ttf",BaseFont.IDENTITY_H,BaseFont.EMBEDDED);
BaseFont bfArialBlack = BaseFont.createFont("/font/ariblk.ttf",BaseFont.IDENTITY_H,BaseFont.EMBEDDED);
for (int i=1; i<=reader.getNumberOfPages(); i++){
PdfContentByte over = stamper.getOverContent(i);
//TOP LEFT
over.beginText();
over.setFontAndSize(bfArialBold, 9);
over.setTextMatrix(040, 670);
over.showText("Registry Date: "); //<-----That field/line/text
over.endText();
over.beginText();
over.setFontAndSize(bfArialPlain, 9);
over.setTextMatrix(115, 670);
over.showText("21/07/2016");
over.endText();
over.beginText();
over.setFontAndSize(bfArialBold, 9);
over.setTextMatrix(040, 660);
over.showText("Validation Date: "); //<-----And that one
over.endText();
over.beginText();
over.setFontAndSize(bfArialPlain, 9);
over.setTextMatrix(115, 660);
over.showText("21/07/2016");
over.endText();
//TOP RIGHT...
//...
//...
}
File myFile = new File("C:\\Users\\FIREFENIX\\Documents\\NetBeansProjects\\Java\\PDFCreator\\src\\pdf\\watermarkFinal.pdf");
Desktop.getDesktop().open(myFile);
//////////PRINT DISABLED////////Desktop.getDesktop().print(myFile);
stamper.close();
reader.close();
} catch (IOException | DocumentException ex) {
Logger.getLogger(PDFCreator.class.getName()).log(Level.SEVERE, null, ex);
}
}
I need to have thoose 2 lines underlined.
How can I do it?
There is any other way I can do this easyer?
Thanks.
You are using the very difficult way to add content. There's a much easier way as explained in the official documentation: How to add text at an absolute position on the top of the first page?
Instead of:
cb.BeginText();
cb.MoveText(700, 30);
cb.SetFontAndSize(bf, 12);
cb.ShowText("My status");
cb.EndText();
Use:
ColumnText ct = new ColumnText(stamper.getOverContent(i));
ct.setSimpleColumn(new Rectangle(30, 600, 523, 720));
ct.addElement(new Paragraph("My status"));
ct.go();
If you want to underline text, you need to use a Chunk as is done in this FAQ entry: Strikethrough in cell using itext in Android/Java
So let's adapt the previous snippet:
ColumnText ct = new ColumnText(stamper.getOverContent(i));
ct.setSimpleColumn(new Rectangle(30, 600, 523, 720));
Chunk c = new Chunk("Underlined text");
c.setUnderline(1.5f, -1);
ct.addElement(new Paragraph(c));
ct.go();
For more info, see Absolute positioning of text and the search results for underline.

Unicode unknown on jboss server [duplicate]

when I want to use a font is iText I do the following:
protected final static Font FONT_SIZE_11_BOLD = new Font(Font.HELVETICA, 11f, Font.BOLD);
and then I can use it whereever I want, as follows:
monthSize11 = new Chunk(month, FONT_SIZE_11_BOLD);
I want to use Arial instead of HELVETICA, but Arial is not directly available.
I mean, I cannot do
new Font(Font.ARIAL, 11f, Font.BOLD);
because Arial is not defined at the Font class, but the Arial.ttf file is at my System under C:\WINDOWS\Fonts.
The question is how I can bind the Arial.ttf file to iText and how can I use it.
Many thnaks in advance.
EDIT: I would like to use own fonts. I mean, I have a file called "myCompany.ttf" where own fonts have been defined and at some places I must use. The problem is not only with Arial.
BaseFont base = BaseFont.createFont("c:/windows/fonts/arial.ttf", BaseFont.WINANSI);
Font font = new Font(base, 11f, Font.BOLD);
....
Read more here.
Load it from inside the JAR using a leading slash; otherwise, use the absolute path of your font (C:\...\fonts\Sansation_Regular.ttf). For example:
Font font = FontFactory.getFont("/fonts/Sansation_Regular.ttf",
BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 0.8f, Font.NORMAL, BaseColor.BLACK);
BaseFont baseFont = font.getBaseFont();
The relative path of the font is: 'src/main/resources/fonts'
Using Itext 5.4.5
Example code
Use BaseFont.createFont to create a new Font object.
You can pass any Type1 or TTF font. You will just have to ensure your font file is distributed alongwith.
Refer
BaseFont API
Creating custom fonts using itext is simple
I had written code for the same below
Will definitely help someone
public class CustomFontStyle {
public static void main(String[] args) {
// creation of the document with a certain size and certain margins
// may want to use PageSize.LETTER instead
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
try {
// creation of the different writers
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("CustomFontsStyle.pdf"));
final String NEWLINE = "\n";
document.open();
Phrase phrase = new Phrase();
BaseFont baseFont3 = BaseFont.createFont("Xenotron.ttf", BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
Font font2 = new Font(baseFont3, 12);
document.add(new Paragraph("Custom Xenotron Font: ", font2));
phrase.add(NEWLINE);
document.add(phrase);
document.close();
}
catch (Exception ex) {
System.err.println(ex.getMessage());
}
}
}

Java Set local file Hyperlink in existing pdf using itext

I am trying to provide a hyper link in a existing PDF, which when clicked will open the file. How can this be done?
I have try following Code it work fine for external hyper link like http://www.google.com but not working for local file hyperlink like D:/intro.pdf .
i am using itext pdf library.
Code :
String in = "D:/introduction.pdf";
String out = "D:/introduction.pdf";
try {
PdfReader reader = new PdfReader(in);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper(reader, baos);
PdfContentByte canvas=stamper.getOverContent(6);
Chunk imdb = new Chunk("Local Link");
imdb.setAnchor("http://www.google.com"); // this work
// imdb.setAnchor("D://intro.pdf"); // this does not work
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(imdb), 100, 10, 0);
stamper.close();
FileOutputStream fileOutputStream = new FileOutputStream(out);
IOUtils.write(baos.toByteArray(), fileOutputStream);
} catch (Exception e) {
}
i have also try using Annotation as below :
PdfAnnotation annotation;
PdfName aa=new PdfName("test test");
annotation = PdfAnnotation.createLink(stamper.getWriter(),
new Rectangle(50f, 750f, 180f, 800f),aa,PdfAction.gotoRemotePage("file:///D:/intro.pdf","1", false, true));
annotation.setTitle("Click Here");
stamper.addAnnotation(annotation, 1);
I have also try below code comment by #Bruno Lowagie : [ it create link on given page but in intro.pdf file and when i click on link it on same page (intro.pdf)]
as per above image ( image of intro.pdf page number-2 )
PdfReader reader1 = new PdfReader("D://introduction.pdf");
PdfStamper stamper1 = new PdfStamper(reader1, new FileOutputStream("D://intro.pdf"));
PdfAnnotation link1 = PdfAnnotation.createLink(stamper1.getWriter(),
new Rectangle(136, 780, 559, 806), PdfAnnotation.HIGHLIGHT_INVERT,
new PdfAction("D://introduction.pdf", 1));
link1.setTitle("Click Here");
stamper1.addAnnotation(link1, 2);
stamper1.close();
Thanks in advance.
You need to specify the protocol. For web pages, your URI starts with http://; for files your URI should start with file://.
However, as the file you want to link to is also a PDF file, you probably don't want to use the setAnchor() method. You should use the setRemoteGoto() method instead. See the MovieLinks2 example.
If you want to add a link to an existing document, this is how to do it:
PdfReader reader = new PdfReader("hello.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("hello_link.pdf"));
PdfAnnotation link = PdfAnnotation.createLink(stamper.getWriter(),
new Rectangle(36, 790, 559, 806), PdfAnnotation.HIGHLIGHT_INVERT,
new PdfAction("hello.pdf", 1));
stamper.addAnnotation(link, 1);
stamper.close();
If you look inside the PDF document, you'll see that the new file named hello_link.pdf contains a Link annotation that refers to the old file hello.pdf:

How to add new fonts to Itext using java

when I want to use a font is iText I do the following:
protected final static Font FONT_SIZE_11_BOLD = new Font(Font.HELVETICA, 11f, Font.BOLD);
and then I can use it whereever I want, as follows:
monthSize11 = new Chunk(month, FONT_SIZE_11_BOLD);
I want to use Arial instead of HELVETICA, but Arial is not directly available.
I mean, I cannot do
new Font(Font.ARIAL, 11f, Font.BOLD);
because Arial is not defined at the Font class, but the Arial.ttf file is at my System under C:\WINDOWS\Fonts.
The question is how I can bind the Arial.ttf file to iText and how can I use it.
Many thnaks in advance.
EDIT: I would like to use own fonts. I mean, I have a file called "myCompany.ttf" where own fonts have been defined and at some places I must use. The problem is not only with Arial.
BaseFont base = BaseFont.createFont("c:/windows/fonts/arial.ttf", BaseFont.WINANSI);
Font font = new Font(base, 11f, Font.BOLD);
....
Read more here.
Load it from inside the JAR using a leading slash; otherwise, use the absolute path of your font (C:\...\fonts\Sansation_Regular.ttf). For example:
Font font = FontFactory.getFont("/fonts/Sansation_Regular.ttf",
BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 0.8f, Font.NORMAL, BaseColor.BLACK);
BaseFont baseFont = font.getBaseFont();
The relative path of the font is: 'src/main/resources/fonts'
Using Itext 5.4.5
Example code
Use BaseFont.createFont to create a new Font object.
You can pass any Type1 or TTF font. You will just have to ensure your font file is distributed alongwith.
Refer
BaseFont API
Creating custom fonts using itext is simple
I had written code for the same below
Will definitely help someone
public class CustomFontStyle {
public static void main(String[] args) {
// creation of the document with a certain size and certain margins
// may want to use PageSize.LETTER instead
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
try {
// creation of the different writers
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("CustomFontsStyle.pdf"));
final String NEWLINE = "\n";
document.open();
Phrase phrase = new Phrase();
BaseFont baseFont3 = BaseFont.createFont("Xenotron.ttf", BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
Font font2 = new Font(baseFont3, 12);
document.add(new Paragraph("Custom Xenotron Font: ", font2));
phrase.add(NEWLINE);
document.add(phrase);
document.close();
}
catch (Exception ex) {
System.err.println(ex.getMessage());
}
}
}

Categories