IText - Generating PDF with Chinese characters (Chinese Simplified) - java

I am using iText to generate some PDFs, these pdfs have some Chinese characters (Simplified Chinese - GB2312), however I am unable to generate a pdf with these characters.
Anyone could tell me where I am wrong?
I tried using various forms of creation but did not succeed:
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
com.itextpdf.text.DocumentException: Font 'STSong-Light' with 'UniGB-UCS2-H' is not recognized.
at com.itextpdf.text.pdf.BaseFont.createFont(BaseFont.java:699)
at com.itextpdf.text.pdf.BaseFont.createFont(BaseFont.java:606)
at com.itextpdf.text.pdf.BaseFont.createFont(BaseFont.java:441)
at com.ford.fc.frc.render.wsltopdf.PDFDefaultWriter.printText(PDFDefaultWriter.java:176)
at com.ford.fc.frc.render.wsltopdf.PDFDefaultConverter.convertFile(PDFDefaultConverter.java:122)
at com.ford.fc.frc.render.wsltopdf.PDFDefaultConverter.convert(PDFDefaultConverter.java:234)
at com.ford.fc.frc.render.plugins.PDFDefaultRenderer.render(PDFDefaultRenderer.java:41)
at com.ford.fc.frc.report.ReportManager.executeRenderer(ReportManager.java:1113)
at com.ford.fc.frc.report.ReportManager.reportCompleted(ReportManager.java:596)
at com.ford.fc.roc.ReportOutputControl.reportCompleted(ReportOutputControl.java:87)
at LoadFRC.main(LoadFRC.java:69)
BaseFont bfComic = BaseFont.createFont(AsianFontMapper.ChineseSimplifiedFont, AsianFontMapper.ChineseSimplifiedEncoding_H, BaseFont.NOT_EMBEDDED);
Font fontbold = new Font(bfComic, 8);
BaseFont bfComic = BaseFont.createFont("C:\\Windows\\Fonts\\cour.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font fontbold = new Font(bfComic, 8);
Could someone help me?
Adding question, this is my current code for testing:
while(null != (line = reader.readLine())) {
document.open();
FontSelector selector = new FontSelector();
/*FontFactory.getFont("MSung-Light","UniCNS-UCS2-H", BaseFont.NOT_EMBEDDED);*/
Font f2 = FontFactory.getFont(AsianFontMapper.ChineseSimplifiedFont, AsianFontMapper.ChineseTraditionalEncoding_H, BaseFont.NOT_EMBEDDED);
f2.setColor(BaseColor.RED);
selector.addFont(f2);
Phrase ph = selector.process(line);
document.add(new Paragraph(ph));
BaseFont bfComic = BaseFont.createFont("C:\\Windows\\Fonts\\arialuni.ttf", BaseFont.IDENTITY_V, BaseFont.EMBEDDED);
Font fontbold = new Font(bfComic, 8);
Paragraph p = new Paragraph(line, fontbold);
document.add(p);
// step 5: we close the document
}

The solution adopted:
private static final String PATH_FONT_ARIALUNI = "C:\\Windows\\Fonts\\arialuni.ttf";
private static final String PATH_FONT_COUR = "C:\\Windows\\Fonts\\cour.ttf";
// FOR Chinese
BaseFont baseFont = BaseFont.createFont(PATH_FONT_ARIALUNI, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font font = new Font(baseFont, 6.8f);
BaseFont baseFontNormal = BaseFont.createFont(PATH_FONT_COUR, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font fontNormal = new Font(baseFontNormal, 6.8f);
Paragraph par = new Paragraph();
par.setLeading(9);
char[] aa = line.toCharArray();
boolean isLastChineseChar = false;
System.out.println(line);
StringBuilder newLine = new StringBuilder();
for (int j = 0; j < line.length(); j++) {
if((Character.UnicodeBlock.of(aa[j]) == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS)){
if(!isLastChineseChar) {
par.add(new Phrase(newLine.toString(), fontNormal));
newLine.delete(0, newLine.length());
}
newLine.append(aa[j]);
isLastChineseChar = true;
/*System.out.println("Is CHINESE: " + aa[j]);*/
} else {
if(isLastChineseChar) {
par.add(new Phrase(newLine.toString(), font));
newLine.delete(0, newLine.length());
isLastChineseChar = false;
}
newLine.append(aa[j]);
/*System.out.println("NOT IS CHINESE: " + aa[j]);*/
}
}
if(isLastChineseChar){
par.add(new Phrase(newLine.toString(), font));
} else {
par.add(new Phrase(newLine.toString(), fontNormal));
}
if(line.contains(BREAK_PAGE)) {
document.newPage();
}
par.setAlignment(Element.ALIGN_LEFT);
document.add(par);

You have the iText jar in your CLASSPATH, but you forgot to add the (correct) itext-asian.jar.
Please download version 2.3 of the extra jars ZIP-file that is available here: http://sourceforge.net/projects/itext/files/extrajars/
This jar contains metrics for Chinese glyphs. Such a font will never be embedded. When you open a document using such a font in Adobe Reader, you may be asked to install an extra font pack.

Related

Non removable watermark on PDF file using iText in Java

We have a requirement where we need to add text watermark on magazines which has multiple rich images on each page. I tried com.itextpdf.jar version 5.0.6 to add the watermark but eventually I am able to remove it using Adobe Acrobat Pro.
I tried below option also but that too didn't work.
stamper.setFreeTextFlattening(true);
Is it possible with iText to add a watermark which can not be removed without much effort.
Below is my implementation.
public static void addWaterMark() throws IOException, DocumentException {
PdfReader reader = new PdfReader("C:/Trade-catalog/Catalog2017.pdf");
ByteArrayOutputStream outputPdf = new ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper(reader, outputPdf);
String bodyWatermarkText = "12345 - John Smith";
String bodyWatermarkRotation = "35";
String footerWatermarkText = "Richard Parker";
BaseFont font = BaseFont.createFont("/fonts/micross.ttf", "Cp1250", BaseFont.EMBEDDED);
PdfGState state = new PdfGState();
state.setFillOpacity(0.3f);
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
Rectangle thisPageSize = reader.getPageSize(i);
PdfPatternPainter bodyPainter = stamper.getOverContent(i).createPattern(thisPageSize.getWidth(),
thisPageSize.getHeight());
bodyPainter.setColorFill(new BaseColor(0, 0, 0));
bodyPainter.beginText();
bodyPainter.setTextRenderingMode(PdfPatternPainter.TEXT_RENDER_MODE_FILL);
bodyPainter.setFontAndSize(font, 60);
bodyPainter.showTextAlignedKerned(Element.ALIGN_CENTER, bodyWatermarkText, thisPageSize.getWidth() / 2,
thisPageSize.getHeight() / 2, Integer.valueOf(bodyWatermarkRotation));
bodyPainter.showTextAlignedKerned(Element.ALIGN_RIGHT, footerWatermarkText, thisPageSize.getWidth() * 0.97f,
thisPageSize.getHeight() * 0.015f, 0);
bodyPainter.endText();
PdfContentByte overContent = stamper.getOverContent(i);
overContent.setGState(state);
overContent.setColorFill(new PatternColor(bodyPainter));
overContent.rectangle(thisPageSize.getLeft(), thisPageSize.getBottom(), thisPageSize.getWidth(),
thisPageSize.getHeight());
overContent.fill();
overContent.setFlatness(100);
}
stamper.close();
FileOutputStream outputStream = new FileOutputStream(
"C:/Trade-catalog/output/TradeCatalog2017Watermarked_bodyPainter.pdf");
outputPdf.writeTo(outputStream);
outputPdf.close();
reader.close();
}

How to display Arabic in PDF created using iText in android

I am using iText 5.5.10 to create a PDF. When I use English words it works fine, but when I use Arabic words it shows empty lines.
What is the problem, and how can I solve it? Thanks in advance.
public void createPDF1(View view) throws IOException, DocumentException {
// BaseFont urName = BaseFont.createFont("assets/subFolder/fontName.TTF", "UTF-8",BaseFont.EMBEDDED);
// Font urFontName = new Font(urName, 12);
Font font = FontFactory.getFont("Simplified Arabic", BaseFont.IDENTITY_H, true, 22, Font.BOLD);
EditText et=(EditText)findViewById(R.id.txt_input);
BaseFont ArialBase = BaseFont.createFont("assets/tahoma.ttf", BaseFont.IDENTITY_H, true);
Font ArialFont = new Font(ArialBase, 20);
// Font f = FontFactory.getFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font chapterFont = FontFactory.getFont("assets/arialuni.ttf", BaseFont.IDENTITY_H, 16, Font.BOLDITALIC);
Font f=new Font(Font.FontFamily.TIMES_ROMAN,50.0f,Font.UNDERLINE,BaseColor.RED);
Document document = new Document();
String outpath= Environment.getExternalStorageDirectory()+"/mypdf1.pdf";
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outpath));
document.open();
Phrase p = new Phrase("This is incorrect:احمد",ArialFont);
p.add(new Chunk("احمد",ArialFont));
p.add(new Chunk(": 50.00 USD"));
document.add(p);
p = new Phrase("This is correct: ");
p.add(new Chunk("#"+et.getText().toString(),chapterFont));
p.add(new Phrase(": 50.00"));
ColumnText canvas = new ColumnText(writer.getDirectContent());
canvas.setSimpleColumn(36, 750, 559, 780);
canvas.setRunDirection(PdfWriter.RUN_DIRECTION_LTR);
canvas.addElement(p);
canvas.go();
document.close();
}
I have tried the suggestions in this post, but it doesn't work.

Write Heart Symbol in pdf using itext java

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

Itext New Font with Bold and Underline

I am trying to add new font to my pdf which I need to make it bold and underlined..
I can add the new Font, but cannot make it bold and underlined at same time.
I tried the following way..
public class PdfGenerator {
private static final String BASE_FONT = "Trebuchet MS";
private static final String BASE_FONT_BOLDITALIC = "Trebuchet MS BI";
private static final String BASE_FONT_BOLD = "Trebuchet MS B";
private static final Font titlefontSmall = FontFactory.getFont(
BASE_FONT_BOLD, 10, Font.UNDERLINE);
static {
String filePath = "..my font directory";
String fontPath = filePath + "\\" + "trebuc.ttf";
String fontPathB = filePath + "\\" + "TREBUCBD.TTF";
String fontPathBI = filePath + "\\" + "TREBUCBI.TTF";
FontFactory.register(fontPath, BASE_FONT);
FontFactory.register(fontPathB, BASE_FONT_BOLD);
FontFactory.register(fontPathBI, BASE_FONT_BOLDITALIC);
}
public void genMyPdf(String filePath) {
try {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(filePath));
document.open();
Paragraph p = new Paragraph("This should be bold & underline",
titlefontSmall);
document.add(p);
document.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
What am I doing wrong ?
you can define a font object with both styles :
private static final Font SUBFONT = new Font(Font.getFamily("TIMES_ROMAN"), 12, Font.BOLD|Font.UNDERLINE);
Read up on HERE since you are using the IText library.
Basically use chunks then add those chunks to the document.
Chunk underline = new Chunk("Underline. ");
underline.setUnderline(0.1f, -2f); //0.1 thick, -2 y-location
document.add(underline);
I haven't tried it myself so I don't know how it turns out yet. Further reading up on the iText documentation, it seems that you have to define a bold font first and then implement it. THIS TUTORIAL shows an example of bold font usage with iText and making a pdf with bold text. From there, I'm sure you can implement the code above to the bold text and walah!, bold-underlined text :D
You can define your FONT in your class as such:
public final static Font CUSTOM_FONT = new Font(Font.FontFamily.TIMES_ROMAN, 8, Font.BOLD | Font.UNDERLINE);
and then use it as :
paragraph.add(new Phrase( " YOUR TEXT HERE ",PDFCreator.CUSTOM_FONT));
try it
Font fontbold = FontFactory.getFont("Times-Roman", 12, Font.BOLD);
document.add(new Paragraph("Times-Roman, Bold", fontbold));
and Font.UNDERLINE for undeline
You can just use the following to get both bold and underline:-
Chunk buyerOrder = new Chunk("Buyer's Order Number", FontFactory.getFont(FontConstants.TIMES_ROMAN,8,Font.BOLD));
buyerOrder.setUnderline(0.1f, -2f);
Hope it helps! Thanks

Inserting greater than or equal symbol in to an iText PDF, ie >=

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();
}
}

Categories