Trying to write heart symbol in pdf through java code .
This is my input to pdf : ❤️❤️❤️
But pdf generated is empty without anything written.
Using itext to write to pdf.
The Font used is tradegothic_lt_boldcondtwenty.ttf
OutputStream file = new FileOutputStream(fileName);
Document document = new Document(PageSize.A6);
PdfWriter writer = PdfWriter.getInstance(document, file);
document.open();
PdfLayer nested = new PdfLayer("Layer 1", writer);
PdfContentByte cb = writer.getDirectContent();
cb.beginLayer(nested);
ColumnText ct = new ColumnText(cb);
Font font = getFont();
Phrase para1 = new Phrase("❤️❤️❤️",font);
ct.setSimpleColumn(para1,38,0,260,138,15, Element.ALIGN_LEFT);
ct.go();
cb.endLayer();
document.close();
file.close();
private Font getFont() {
final String methodName = "generatePDF";
LOGGER.entering(CLASSNAME, methodName);
Font font = null;
try {
String filename = tradegothic_lt_boldcondtwenty.ttf;
FontFactory.register(filename, filename);
font = FontFactory.getFont(filename, BaseFont.CP1252, BaseFont.EMBEDDED,11.8f);
} catch(Exception exception) {
LOGGER.logp(Level.SEVERE, CLASSNAME, methodName, "Exception Occurred while fetching the Trade Gothic font." + exception);
font = FontFactory.getFont(FontFactory.HELVETICA_BOLD,11.8f);
}
return font;
}
Phrase para1 has the heart correctly. But not able to see in pdf
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 using iText7 - pdfHTML to convert my HTML template into a PDF.
I want to display a Page X of Y on my footer; However, I always getting Page 1 of 1. (There are 20 pages)
Below is my codebase to convert multiple HTML files into PDF.
// Converter Class file
ByteArrayOutputStream outputBaos = new ByteArrayOutputStream();
PdfWriter writer = new PdfWriter(outputBaos);
PdfDocument pdf = new PdfDocument(writer);
PdfMerger merger = new PdfMerger(pdf);
...
for (String template : templates) {
ByteArrayOutputStream tempOutput = new ByteArrayOutputStream();
PdfWriter tempWriter = new PdfWriter(tempOutput);
PdfDocument tempPdf = new PdfDocument(tempWriter);
HtmlConverter.convertToPdf(template, tempPdf, converterProperties);
tempPdf = new PdfDocument(
new PdfReader(
new ByteArrayInputStream(tempOutput.tpByteArray())
)
);
merger.merge(tempPdf, 1, tempPdf.getNumberOfPages());
tempPdf.close();
}
pdf.close();
return outputBaos;
// HTML file
#page {
#bottom-right {
content: "Page " counter(page) " of " counter(pages);
}
}
May I know how can I achieve this?
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
How to add images and design header, footer to pdf using itext?
I have written this ,but getting exception file not found.
Image image = Image.getInstance("\resources\image.gif");
thanks
I used the following code to insert an image from the classpath. Typically useful when you need to include an image that is not accessible from a public url.
Image img = Image.getInstance(getClass().getClassLoader().getResource("MyImage.jpg"));
In my case, I use maven, so I put MyImage.jpg in src/main/resources
take a look at this example
import java.io.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
public class CreatePDF{
public static void main(String arg[])throws Exception{
try{
Document document=new Document();
FileOutputStream fos=new FileOutputStream("C:/header-footer.pdf");
PdfWriter writer = PdfWriter.getInstance(document, fos);
document.open();
Image image1 = Image.getInstance("C:/image1.jpg");
Image image2 = Image.getInstance("C:/image2.jpg");
image1.setAbsolutePosition(0, 0);
image2.setAbsolutePosition(0, 0);
PdfContentByte byte1 = writer.getDirectContent();
PdfTemplate tp1 = byte1.createTemplate(600, 150);
tp1.addImage(image2);
PdfContentByte byte2 = writer.getDirectContent();
PdfTemplate tp2 = byte2.createTemplate(600, 150);
tp2.addImage(image1);
byte1.addTemplate(tp1, 0, 715);
byte2.addTemplate(tp2, 0, 0);
Phrase phrase1 = new Phrase(byte1 + "", FontFactory.getFont(FontFactory.TIMES_ROMAN, 7, Font.NORMAL));
Phrase phrase2 = new Phrase(byte2 + "", FontFactory.getFont(FontFactory.TIMES_ROMAN, 7, Font.NORMAL));
HeaderFooter header = new HeaderFooter(phrase1, true);
HeaderFooter footer = new HeaderFooter(phrase2, true);
document.setHeader(header);
document.setFooter(footer);
document.close();
System.out.println("File is created successfully showing header and footer.");
}
catch (Exception ex){
System.out.println(ex);
}
}
}
Does anyone know an easy way to include the greater than or equal symbol in an iText PDF document without resorting to custom fonts?
You need to add the unicode for this character. Also make sure that the char is included in the font you use.
document.add( new Paragraph("\u2265"));
Use the below code for the same. It's work for me.
//symbol for greater or equal then
public void process() throws DocumentException, IOException {
String dest = "/home/ashok/ashok/tmp/hello.pdf";
BaseFont bfont = BaseFont.createFont(
"/home/ashok/ashok/fonts/Cardo-Regular.ttf",
BaseFont.IDENTITY_H,
BaseFont.EMBEDDED);
Font font = new Font(bfont, 12);
try {
Document document=new Document();
PdfWriter.getInstance(document,new
FileOutputStream("/home/ashok/ashok/tmp/hello.pdf"));
document.open();
Chunk chunk = new Chunk("\u2265");
Paragraph p = new Paragraph("Mathematical Operators are ",font);
p.add(chunk);
document.add(p);
p = new Paragraph(" ",font);
chunk = new Chunk("\u2264");
p.add(chunk);
document.add(p);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}