How to display Arabic in PDF created using iText in android - java

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.

Related

Center and format text with OpenPDF

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

itext xmlworker doesn't work with custom font family

My application parses html and put the content in pdf, now it needs to support multiple fonts ex: Myanmar and Chinese.
I am able to do this with phrases but not with html even for single font family
Working Code
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("/home/a2.pdf"));
Font font = FontFactory.getFont("KozMinPro-Regular", "UniJIS-UCS2-H", false);
Font font1 = FontFactory.getFont("/home/mm3.ttf", BaseFont.IDENTITY_H, false);
FontSelector fs = new FontSelector();
fs.addFont(font);
fs.addFont(font1);
Phrase phrase = fs.process("長");
phrase.add(fs.process("၀န္ထမ္းလစလႊာ( လ )"));
phrase.add(fs.process("123aab"));
document.open();
document.add(phrase);
document.close();
Tried with XMLWorker but it didn't work:
final MyFontFactory fontFactory = new MyFontFactory();
FontFactory.register("/home/Downloads/mm3.ttf");
FontFactory.setFontImp(fontFactory);
final HtmlPipelineContext htmlContext = new HtmlPipelineContext(new CssAppliersImpl(fontFactory));
final CSSResolver cssResolver = XMLWorkerHelper.getInstance().getDefaultCssResolver(true);
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("/home/a2.pdf"));
document.open();
String str="<span style=\"font-family: "Open Sans", sans-serif; white-space: pre-wrap; background-color: rgb(255, 255, 255);\">Deduc၀န္ထမ္းလစာေပးေခ်လႊာ( လစာငွေ )tions哈罗</span> ";
XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
InputStream is = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
worker.parseXHtml(writer, document, is, Charset.forName("UTF-8"));
// step 5
document.close();

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 - Generating PDF with Chinese characters (Chinese Simplified)

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.

Outputstream - create non editable pdf file

Below code is for writing pdf file;
BaseFont bf = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
FontSelector fs = new FontSelector();
fs.addFont(new Font(bf));
String fileName = filePath3 + "//DEVIATION_REPORT.pdf";
OutputStream file = new FileOutputStream(new File(fileName));
Font smallFont = new Font(Font.FontFamily.COURIER, 6, Font.NORMAL);
Font headerFont = new Font(Font.FontFamily.HELVETICA, 7, Font.BOLD);
Font tabFont = new Font(Font.FontFamily.HELVETICA, 5, Font.NORMAL);
Font rusFont = new Font(bf, 5);
Font blueFont = new Font(bf, 5);
blueFont.setColor(BaseColor.BLUE);
Font redFont = new Font(bf, 5);
redFont.setColor(BaseColor.RED);
String comType;
if (compType == 2)
comType = "Character";
else
comType = "Word";
Document doc = new Document();
PdfWriter.getInstance(doc, file);
doc.open();
Image image1 = Image.getInstance(cmdpath + "ScRp.jpg");
image1.setAlignment(Element.ALIGN_LEFT);
Paragraph prg = new Paragraph("Compare", smallFont);
prg.setAlignment(Element.ALIGN_RIGHT);
doc.add(image1);
doc.add(prg);
doc.add(new Paragraph("__________________________________________________"));
doc.add(new Paragraph("Passed Report"));
doc.add(new Paragraph(" "));
PdfPTable table = new PdfPTable(2);
PdfPCell cell1 = new PdfPCell(new Paragraph("No", headerFont));
cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
cell1.setPaddingBottom(5);
PdfPCell cell2 = new PdfPCell(new Paragraph("Details", headerFont));
cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
cell2.setPaddingBottom(5);
table.addCell(cell1);
table.addCell(cell2);
doc.add(table);
doc.newPage();
doc.close();
file.close();
How do I do if i want to make the pdf is non editable. I've tried to use
PdfEncryptor.encrypt(
new PdfReader(fileName),
new FileOutputStream("HelloWorldProtected.pdf"),
null,
"StrongPassword".getBytes(),
PdfWriter.AllowPrinting,
PdfWriter.STRENGTH128BITS);
but compiler stops here. I waited more than 15 minutes but nothing happen.
I even make file.setreadOnly(), but it doesn't user to save it after edit. It still allow user to edit. User can Save AS the document and replace with the non editable one.
Is there any other way we can make the file as non editable. Please advice.
You might want to use iText for such kind of work if its fine with your project. I cant see any other option as if now. I have personally used iText and it is quite robust. let me know if this helps.
Edit:
Encryption settings
http://viralpatel.net/blogs/password-protect-pdf-itext-java/
http://www.jarfinder.com/index.php/java/info/com.lowagie.text.pdf.interfaces.PdfEncryptionSettings
Try searching more on google and SO
EDIT: The long waiting of 15 min. problem might be of file write permissions on your file path.

Categories