Pdf generation in arabic language is printing garbage values - pdf

I am using component one library to generate pdf document and save in phone storage. Here is my code to print just one line.
public ViewStatementDetails()
{
this.InitializeComponent();
this.navigationHelper = new NavigationHelper(this);
this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
this.navigationHelper.SaveState += this.NavigationHelper_SaveState;
pdf = new C1PdfDocument(PaperKind.Letter);
pdf.Clear();
}
private void Print_Click(object sender, RoutedEventArgs e)
{
LoadingProgress.Visibility = Windows.UI.Xaml.Visibility.Visible;
PDFTest_Loaded();
}
async void PDFTest_Loaded()
{
try
{
WriteableBitmap writeableBmp = await initializeImage();
pdf = new C1PdfDocument(PaperKind.Letter);
CreateDocumentText(pdf);
StorageFile Assets = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("Salik Statement.pdf", CreationCollisionOption.GenerateUniqueName);
PdfUtils.Save(pdf, Assets);
LoadingProgress.Visibility = Visibility.Collapsed;
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
Debugger.Break();
LoadingProgress.Visibility = Visibility.Collapsed;
}
}
async void CreateDocumentText(C1PdfDocument pdf)
{
try
{
pdf.Landscape = false;
// measure and show some text
var text = App.GetResource("RoadAndSafetyheading")
var font = new Font("Segoe UI Light", 36, PdfFontStyle.Bold);
var fmt = new StringFormat();
fmt.Alignment = HorizontalAlignment.Center;
// measure it
var sz = pdf.MeasureString(text, font, 72 * 3, fmt);
var rc = new Rect(0, 0, pdf.PageRectangle.Width, sz.Height);
rc = PdfUtils.Offset(rc, 0, 0);
// draw the text
pdf.DrawString(text, font, Colors.Orange, rc, fmt);
}
catch (Exception e)
{
}
}
The above code is working perfect but my application supports two languages, English and Arabic. And when I am in arabic mode and generate same pdf it prints garbage values in pdf file. attaching image of printed characters.

Use of Arabic characters would require to use Unicode symbols and embed the Unicode font into PDF (as PDF format does not provide support for Unicode using its built-in fonts). If you are using ComponentOne then try to set .EmbedTrueTypeFonts = true (see details here)

Related

Webdings font characters not extracted using pdfbox

I am using pdfbox to get the names of all fonts that are used in a pdf.
So far it was working well. However, I recently came across a pdf that has 'Webdings' font. PDFBox was not able to identify it.Could anyone help please.
This is the code I have used:
public static Set<String> extractFonts(String pdfPath) throws IOException
{
PDDocument doc = PDDocument.load(new File(pdfPath));
PDPageTree pages = doc.getDocumentCatalog().getPages();
Set<String> fontSet = new HashSet<String>();
try{
for(PDPage page:pages){
PDResources res = page.getResources();
for (COSName fontName : res.getFontNames())
{
PDFont font = res.getFont(fontName);
if(font != null){
String fontUsedName = font.getName();
if(fontUsedName.contains("+")) {
fontUsedName = fontUsedName.substring(fontUsedName.indexOf("+")+1, fontUsedName.length());
}
fontSet.add(fontUsedName);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(fontSet);
return fontSet;
}
I was able to know that the font 'Webdings' is present from the File-> Properties->Fonts option in Adobe Reader

Generating PDF with iText and batik

I'm trying to export text and SVG graphs to a PDF. I found out that iText and batik can do this. So I tried doing that, but everytime I put in a graph, it would become extraordinary small.
I thought it might be something with my code, so I figured I would try an examplecode from Vaadin.
public class PdfExportDemo {
private String fontDirectory = null;
private final String baseFont = "Arial";
private PdfWriter writer;
private Document document;
private Font captionFont;
private Font normalFont;
private String svgStr;
/**
* Writes a PDF file with some static example content plus embeds the chart
* SVG.
*
* #param pdffilename
* PDF's filename
* #param svg
* SVG as a String
* #return PDF File
*/
public File writePdf(String pdffilename, String svg) {
svgStr = svg;
document = new Document();
document.addTitle("PDF Sample");
document.addCreator("Vaadin");
initFonts();
File file = null;
try {
file = writeToFile(pdffilename, document);
document.open();
writePdfContent();
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
/**
* Get Font directory that will be checked for custom fonts.
*
* #return Path to fonts
*/
public String getFontDirectory() {
return fontDirectory;
}
/**
* Set Font directory that will be checked for custom fonts.
*
* #param fontDirectory
* Path to fonts
*/
public void setFontDirectory(String fontDirectory) {
this.fontDirectory = fontDirectory;
}
private void initFonts() {
if (fontDirectory != null) {
FontFactory.registerDirectory(fontDirectory);
}
captionFont = FontFactory.getFont(baseFont, 10, Font.BOLD, new Color(0,
0, 0));
normalFont = FontFactory.getFont(baseFont, 10, Font.NORMAL, new Color(
0, 0, 0));
}
private File writeToFile(String filename, Document document)
throws DocumentException {
File file = null;
try {
file = File.createTempFile(filename, ".pdf");
file.deleteOnExit();
FileOutputStream fileOut = new FileOutputStream(file);
writer = PdfWriter.getInstance(document, fileOut);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
private void writePdfContent() throws DocumentException, IOException {
Paragraph caption = new Paragraph();
caption.add(new Chunk("Vaadin Charts Export Demo PDF", captionFont));
document.add(caption);
Paragraph br = new Paragraph(Chunk.NEWLINE);
document.add(br);
Paragraph paragraph = new Paragraph();
paragraph.add(new Chunk("This PDF is rendered with iText 2.1.7.",
normalFont));
document.add(paragraph);
paragraph = new Paragraph();
paragraph
.add(new Chunk(
"Chart below is originally an SVG image created with Vaadin Charts and rendered with help of Batik SVG Toolkit.",
normalFont));
document.add(paragraph);
document.add(createSvgImage(writer.getDirectContent(), 400, 400));
document.add(createExampleTable());
}
private PdfPTable createExampleTable() throws BadElementException {
PdfPTable table = new PdfPTable(2);
table.setHeaderRows(1);
table.setWidthPercentage(100);
table.setTotalWidth(100);
// Add headers
table.addCell(createHeaderCell("Browser"));
table.addCell(createHeaderCell("Percentage"));
// Add rows
table.addCell(createCell("Firefox"));
table.addCell(createCell("45.0"));
table.addCell(createCell("IE"));
table.addCell(createCell("26.8"));
table.addCell(createCell("Chrome"));
table.addCell(createCell("12.8"));
table.addCell(createCell("Safari"));
table.addCell(createCell("8.5"));
table.addCell(createCell("Opera"));
table.addCell(createCell("6.2"));
table.addCell(createCell("Others"));
table.addCell(createCell("0.7"));
return table;
}
private PdfPCell createHeaderCell(String caption)
throws BadElementException {
Chunk chunk = new Chunk(caption, captionFont);
Paragraph p = new Paragraph(chunk);
p.add(Chunk.NEWLINE);
p.add(Chunk.NEWLINE);
PdfPCell cell = new PdfPCell(p);
cell.setBorder(0);
cell.setBorderWidthBottom(1);
cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
return cell;
}
private PdfPCell createCell(String value) throws BadElementException {
PdfPCell cell = new PdfPCell(new Phrase(new Chunk(value, normalFont)));
cell.setBorder(0);
cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
return cell;
}
private Image drawUnscaledSvg(PdfContentByte contentByte)
throws IOException {
// First, lets create a graphics node for the SVG image.
GraphicsNode imageGraphics = buildBatikGraphicsNode(svgStr);
// SVG's width and height
float width = (float) imageGraphics.getBounds().getWidth();
float height = (float) imageGraphics.getBounds().getHeight();
// Create a PDF template for the SVG image
PdfTemplate template = contentByte.createTemplate(width, height);
// Create Graphics2D rendered object from the template
Graphics2D graphics = template.createGraphics(width, height);
try {
// SVGs can have their corner at coordinates other than (0,0).
Rectangle2D bounds = imageGraphics.getBounds();
graphics.translate(-bounds.getX(), -bounds.getY());
// Paint SVG GraphicsNode with the 2d-renderer.
imageGraphics.paint(graphics);
// Create and return a iText Image element that contains the SVG
// image.
return new ImgTemplate(template);
} catch (BadElementException e) {
throw new RuntimeException("Couldn't generate PDF from SVG", e);
} finally {
// Manual cleaning (optional)
graphics.dispose();
}
}
/**
* Use Batik SVG Toolkit to create GraphicsNode for the target SVG.
* <ol>
* <li>Create SVGDocument</li>
* <li>Create BridgeContext</li>
* <li>Build GVT tree. Results to GraphicsNode</li>
* </ol>
*
* #param svg
* SVG as a String
* #return GraphicsNode
* #throws IOException
* Thrown when SVG could not be read properly.
*/
private GraphicsNode buildBatikGraphicsNode(String svg) throws IOException {
UserAgent agent = new UserAgentAdapter();
SVGDocument svgdoc = createSVGDocument(svg, agent);
DocumentLoader loader = new DocumentLoader(agent);
BridgeContext bridgeContext = new BridgeContext(agent, loader);
bridgeContext.setDynamicState(BridgeContext.STATIC);
GVTBuilder builder = new GVTBuilder();
GraphicsNode imageGraphics = builder.build(bridgeContext, svgdoc);
return imageGraphics;
}
private SVGDocument createSVGDocument(String svg, UserAgent agent)
throws IOException {
SVGDocumentFactory documentFactory = new SAXSVGDocumentFactory(
agent.getXMLParserClassName(), true);
SVGDocument svgdoc = documentFactory.createSVGDocument(null,
new StringReader(svg));
return svgdoc;
}
private Image createSvgImage(PdfContentByte contentByte,
float maxPointWidth, float maxPointHeight) throws IOException {
Image image = drawUnscaledSvg(contentByte);
image.scaleToFit(maxPointWidth, maxPointHeight);
return image;
}
}
But when I do this, I still get the small graph. I tried debugging the app, and the size og the graph is actually 10000x600, and then it tries to scale it to fit.
So I tried manually setting the size to like 400x600, no dice. I tried forcing the size on the SVG - no dice. And if I make it, I think, too big then it simply shows a small 1x1cm box with shadows. The output from the example is as follows.
I really hope someone can help.
UPDATE
When I remove these two lines:
Rectangle2D bounds = imageGraphics.getBounds();
graphics.translate(-bounds.getX(), -bounds.getY());
and hardcode the sizes, It kinda works. But the image itself is stil enourmous, and can't seem to fit it.
see for example:

Using pdfbox to convert a color PDF to a b/w tiff

I am have a bit of a problem converting some color PDFs to tiff images. The PDFs I am having problems with have hand written signatures written in blue ink. These signatures do not appear in the generated binary tiffs. I suspect there is a threshold value somewhere to determine which pixels will be black and which will be white.
#SuppressWarnings("serial")
private static void convertPdfToTiff(final File pdf, final File tif) throws Exception {
try
{
final Iterator<ImageWriter> imageWriterIterator = ImageIO.getImageWritersByFormatName("TIF");
final ImageWriter imageWriter = imageWriterIterator.hasNext() ? imageWriterIterator.next() : null;
final TIFFImageWriteParam writeParam = new TIFFImageWriteParam(Locale.getDefault());
writeParam.setCompressionMode(TIFFImageWriteParam.MODE_EXPLICIT);
writeParam.setCompressionType("LZW");
PDDocument pdfDocument = PDDocument.load(pdf);
PDFRenderer pdfRenderer = new PDFRenderer(pdfDocument);
OutputStream out = new FileOutputStream(tif);
final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(out);
final ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(bufferedOutputStream);
imageWriter.setOutput(imageOutputStream);
imageWriter.prepareWriteSequence(null);
int pageCounter = 0;
for (PDPage page : pdfDocument.getPages())
{
BufferedImage image = pdfRenderer.renderImageWithDPI(pageCounter, 300, ImageType.BINARY);
final IIOImage s = new IIOImage(image, null, new TIFFImageMetadata(new TIFFIFD(new Vector<BaselineTIFFTagSet>()
{
{
add(BaselineTIFFTagSet.getInstance());
}
})))
{
{
final TIFFImageMetadata tiffMetadata = (TIFFImageMetadata) getMetadata();
final TIFFIFD rootIFD = tiffMetadata.getRootIFD();
final BaselineTIFFTagSet base = BaselineTIFFTagSet.getInstance();
rootIFD.addTIFFField(new TIFFField(base.getTag(BaselineTIFFTagSet.TAG_X_RESOLUTION), TIFFTag.TIFF_RATIONAL, 1, new long[][] { { 300, 1 } }));
rootIFD.addTIFFField(new TIFFField(base.getTag(BaselineTIFFTagSet.TAG_Y_RESOLUTION), TIFFTag.TIFF_RATIONAL, 1, new long[][] { { 300, 1 } }));
}
};
imageWriter.writeToSequence(s, writeParam);
pageCounter++;
}
imageWriter.dispose();
imageOutputStream.flush();
imageOutputStream.close();
bufferedOutputStream.flush();
bufferedOutputStream.close();
pdfDocument.close();
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
throw e;
}
}
I had the same problem (blue signatures) some time ago and I did this:
render to RGB
convert to b/w with a filter from JH Labs (I got pointed to this by a comment in this answer)
I initially tried the dither and the diffusion filter
the filter that worked best for me was the bias part (I think I used 0.3) of the gain filter combined with the diffusion filter.
you can combine two filters with the compound filter.
the jhlabs stuff is not available as .jar file, but you can download the sources and add it to your project
some examples
Btw, save your files not as LZW, but as G4, that'll make them smaller. PDFBox has methods to efficiently save into images, see here. ImageIOUtil.writeImage() will save to G4 compressed TIFF if your BufferedImage is of type BITONAL.
I ended up rendering the image as grayscale and re drawing it to a second bw image.
#SuppressWarnings("serial")
private static void convertPdfToTiff(final File pdf, final File tif) throws Exception {
try
{
final Iterator<ImageWriter> imageWriterIterator = ImageIO.getImageWritersByFormatName("TIF");
final ImageWriter imageWriter = imageWriterIterator.hasNext() ? imageWriterIterator.next() : null;
final TIFFImageWriteParam writeParam = new TIFFImageWriteParam(Locale.getDefault());
writeParam.setCompressionMode(TIFFImageWriteParam.MODE_EXPLICIT);
writeParam.setCompressionType("CCITT T.6");
PDDocument pdfDocument = PDDocument.load(pdf);
PDFRenderer pdfRenderer = new PDFRenderer(pdfDocument);
OutputStream out = new FileOutputStream(tif);
final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(out);
final ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(bufferedOutputStream);
imageWriter.setOutput(imageOutputStream);
imageWriter.prepareWriteSequence(null);
int pageCounter = 0;
for (PDPage page : pdfDocument.getPages())
{
BufferedImage image = pdfRenderer.renderImageWithDPI(pageCounter, 300, ImageType.GRAY);
BufferedImage image2 = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
Graphics2D g = image2.createGraphics();
g.drawRenderedImage(image, null);
g.dispose();
final IIOImage s = new IIOImage(image2, null, new TIFFImageMetadata(new TIFFIFD(new Vector<BaselineTIFFTagSet>()
{
{
add(BaselineTIFFTagSet.getInstance());
}
})))
{
{
final TIFFImageMetadata tiffMetadata = (TIFFImageMetadata) getMetadata();
final TIFFIFD rootIFD = tiffMetadata.getRootIFD();
final BaselineTIFFTagSet base = BaselineTIFFTagSet.getInstance();
rootIFD.addTIFFField(new TIFFField(base.getTag(BaselineTIFFTagSet.TAG_X_RESOLUTION), TIFFTag.TIFF_RATIONAL, 1, new long[][] { { 300, 1 } }));
rootIFD.addTIFFField(new TIFFField(base.getTag(BaselineTIFFTagSet.TAG_Y_RESOLUTION), TIFFTag.TIFF_RATIONAL, 1, new long[][] { { 300, 1 } }));
}
};
imageWriter.writeToSequence(s, writeParam);
pageCounter++;
}
imageWriter.dispose();
imageOutputStream.flush();
imageOutputStream.close();
bufferedOutputStream.flush();
bufferedOutputStream.close();
pdfDocument.close();
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
throw e;
}
}

Pdf file is not viewing in android app

Anyone can help in this code, the pdf file is not loading in app and just showing blank white screen, Logcat showing FileNotFoundExeeption: /storage/sdcard/raw/ourpdf.pdf.
i am trying to make an app that will show information while i click buttons and every button will be active for specific pdf file reading. Any specific help please.
Thanks for help
part1
package com.code.androidpdf;
public class MainActivity extends Activity {
//Globals:
private WebView wv;
private int ViewSize = 0;
//OnCreate Method:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Settings
PDFImage.sShowImages = true; // show images
PDFPaint.s_doAntiAlias = true; // make text smooth
HardReference.sKeepCaches = true; // save images in cache
//Setup above
wv = (WebView)findViewById(R.id.webView1);
wv.getSettings().setBuiltInZoomControls(true);//show zoom buttons
wv.getSettings().setSupportZoom(true);//allow zoom
//get the width of the webview
wv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
{
#Override
public void onGlobalLayout()
{
ViewSize = wv.getWidth();
wv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
pdfLoadImages();//load images
}
private void pdfLoadImages() {
try
{
// run async
new AsyncTask<Void, Void, Void>()
{
// create and show a progress dialog
ProgressDialog progressDialog = ProgressDialog.show(MainActivity.this, "", "Opening...");
#Override
protected void onPostExecute(Void result)
{
//after async close progress dialog
progressDialog.dismiss();
}
#Override
protected Void doInBackground(Void... params)
{
try
{
// select a document and get bytes
File file = new File(Environment.getExternalStorageDirectory().getPath()+"/randompdf.pdf");
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
net.sf.andpdf.nio.ByteBuffer bb = null ;
raf.close();
// create a pdf doc
PDFFile pdf = new PDFFile(bb);
//Get the first page from the pdf doc
PDFPage PDFpage = pdf.getPage(1, true);
//create a scaling value according to the WebView Width
final float scale = ViewSize / PDFpage.getWidth() * 0.95f;
//convert the page into a bitmap with a scaling value
Bitmap page = PDFpage.getImage((int)(PDFpage.getWidth() * scale), (int)(PDFpage.getHeight() * scale), null, true, true);
//save the bitmap to a byte array
ByteArrayOutputStream stream = new ByteArrayOutputStream();
page.compress(Bitmap.CompressFormat.PNG, 100, stream);
stream.close();
byte[] byteArray = stream.toByteArray();
//convert the byte array to a base64 string
String base64 = Base64.encodeToString(byteArray, Base64.DEFAULT);
//create the html + add the first image to the html
String html = "<!DOCTYPE html><html><body bgcolor=\"#7f7f7f\"><img src=\"data:image/png;base64,"+base64+"\" hspace=10 vspace=10><br>";
//loop through the rest of the pages and repeat the above
for(int i = 2; i <= pdf.getNumPages(); i++)
{
PDFpage = pdf.getPage(i, true);
page = PDFpage.getImage((int)(PDFpage.getWidth() * scale), (int)(PDFpage.getHeight() * scale), null, true, true);
stream = new ByteArrayOutputStream();
page.compress(Bitmap.CompressFormat.PNG, 100, stream);
stream.close();
byteArray = stream.toByteArray();
base64 = Base64.encodeToString(byteArray, Base64.DEFAULT);
html += "<img src=\"data:image/png;base64,"+base64+"\" hspace=10 vspace=10><br>";
}
html += "</body></html>";
//load the html in the webview
wv.loadDataWithBaseURL("", html, "text/html","UTF-8", "");
}
catch (Exception e)
{
Log.d("CounterA", e.toString());
}
return null;
}
}.execute();
System.gc();// run GC
}
catch (Exception e)
{
Log.d("error", e.toString());
}
}
}
It is (sadly) not possible to view a PDF that is stored locally in your devices. Android L has introduced the feature. So, to display a PDF , you have two options:
See this answer for using webview
How to open local pdf file in webview in android? (note that this requires an internet connection)
Use a third party pdf Viewer.
You can also send an intent for other apps to handle your pdf.
You can get an InputStream for the file using
getResources().openRawResource(R.raw.ourpdf)
Docs: http://developer.android.com/reference/android/content/res/Resources.html#openRawResource(int)

Modify Printing attribute for Media Name Java Apache FOP API

Am using Apache FOP API to print a document which was working well for a while but now it is trying to print on a legal size paper on tray 1. Am wondering if i can change that to Letter size so that users do not manually have to hit button on the printer to make that happen.
public void printDocument() {
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
PrintRequestAttributeSet aset =
new HashPrintRequestAttributeSet();
PrintService prnSvc = null;
/* locate a print service that can handle it */
PrintService[] pservices =
PrintServiceLookup.lookupPrintServices(null, null);
if (pservices.length > 0) {
int ii = 0;
while (ii < pservices.length) {
System.out.println("Named Printer found: " + pservices[ii].getName());
if (pservices[ii].getName().endsWith("xyz")) {
prnSvc = pservices[ii];
System.out.println("Named Printer selected: " + pservices[ii].getName() + "*");
break;
}
ii++;
}
/* create a print job for the chosen service */
DocPrintJob pj = prnSvc.createPrintJob();
try {
File file = new File("test.pcl");
FileInputStream fis = new FileInputStream(file); //Doc encapsulating the print data
Doc doc = new SimpleDoc(fis, flavor, null);
/* print the doc as specified */
pj.print(doc, aset);
} catch (IOException ie) {
System.err.println(ie);
} catch (PrintException e) {
e.printStackTrace();
System.err.println(e);
}
}
}
Would highly appreciate if anyone can provide any recommendations around the same.
You'll need to specify the paper size by adding it to aset:
aset.add(javax.print.attribute.standard.MediaSizeName.<desired paper size>);
(Javadoc for MediaSizeName). For letter size, use
aset.add(javax.print.attribute.standard.MediaSizeName.NA_LETTER);