I try to generate a pdf with com.itextpdf in android / java. Basically, (text) chat messages shall be transferred to the pdf for archiving the chat.
Using com.itextpdf works fine for text only messages using the font included in com.itextpdf. Unfortunately, emojis are not covered by these fonts and therefore will not be included in the pdf file.
For including emojis a sample is given here. Following the sample code I am not able to generate a pdf file with emojis displaying. I tried different fonts like noto_emoji_regular.ttf or noto_color_emoji_compat.ttf. Some fonts end in a completely white pdf, some in funny signs like in this
screen shot.
This is my code:
public File createPdfDoc() {
final String font_path = "assets/noto_emoji_regular.ttf";
// test strings
String html = new String("<!DOCTYPE html>\n" +
"<html>\n" +
"<body>\n" +
"<span style='font-size:100px;'>π</span>\n" +
"<p>I will display π</p>\n" +
"<p>I will display π test π
</p>\n" +
"</body>\n" +
"</html>");
String s = "\"title\":\"πΊTEST title value π\",\"text\":\"π TEST text value.\"";
File pdfFile = null;
try {
String exportPath = new ExportProvider(weakContext.get()).getExportDirPath() + File.separator
+ generateDocTitle();
PdfWriter pdfWriter = new PdfWriter(exportPath);
PdfDocument pdf = new PdfDocument(pdfWriter);
// testing text 2 pdf
Document doc = new Document(pdf);
Paragraph p = new Paragraph();
PdfFont emoji_font = PdfFontFactory.createFont(FONT_ACCESS); //Create Pdf Font with Emoji glyphs
p.setFont(emoji_font); //add font to Paragraph
p.setFontSize(15);
p.add(new Text(String.format("Here are some emojis: %s %s", 0x1F600, encodeCodepoint(0x1F604)))); //encode unicode values
doc.add(p); //add Paragraph to document
doc.close();
/*
// testing html 2 pdf
ConverterProperties cprop = new ConverterProperties();//ConverterProperties will be used to add the FontProvider to the Converter.
FontProvider provider = new FontProvider();//The FontProvider will hold our emoji font
provider.addStandardPdfFonts();
provider.addFont("/font/noto_emoji_regular.ttf", PdfEncodings.IDENTITY_H);
cprop.setFontProvider(provider);//add provider to properties
HtmlConverter.convertToPdf(new ByteArrayInputStream(html.getBytes()), pdf, cprop);//Include ConverterProperties as argument for the #convertToPdf() method.
pdf.close();
*/
pdfFile = new File(exportPath);
} catch (IOException e) {
e.printStackTrace();
}
return pdfFile;
}
Can you give me any hint what I have to do for displaying text and emojis?
EDIT: The goal it to export chat messages including emojis to a pdf document. Any alternative idea how to do that is very welcome.
Related
I am working on a pdf editor.
I have made my changes on pdf files with OpenPDF core that is based on iText
And I am viewing the Pdf file with AndroidPdfViewer
My problems are:
Adding new annotations like text or tags or icons into an existing pdf file. ( SOLVED )
Show new changes right after annotations added into pdf file.( SOLVED )
Convert user click into Pdf file coordinates to add new annotation based on user clicked location.
Get click event on added annotations and read meta data that added into that annotation , for ex: read tag hash id that sets on icon annotation. ( SOLVED )
Remove added annotation from PDF File.
Any help appreciated
UPDATE
========================================================================
Solution 1: Adding annotations
Here is my code snippet for adding icon annotation into existing pdf file.
public static void addWatermark(Context context, String filePath) throws FileNotFoundException, IOException {
// get file and FileOutputStream
if (filePath == null || filePath.isEmpty())
throw new FileNotFoundException();
File file = new File(filePath);
if (!file.exists())
throw new FileNotFoundException();
try {
// inout stream from file
InputStream inputStream = new FileInputStream(file);
// we create a reader for a certain document
PdfReader reader = new PdfReader(inputStream);
// get page file number count
int pageNumbers = reader.getNumberOfPages();
// we create a stamper that will copy the document to a new file
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(file));
// adding content to each page
int i = 0;
PdfContentByte under;
// get watermark icon
Image img = Image.getInstance(PublicFunction.getByteFromDrawable(context, R.drawable.ic_chat));
img.setAnnotation(new Annotation("tag", "gd871394bh2c3r", 0, 0, 0, 0));
img.setAbsolutePosition(230, 190);
img.scaleAbsolute(50, 50);
while (i < pageNumbers) {
i++;
// watermark under the existing page
under = stamp.getUnderContent(i);
under.addImage(img);
}
// closing PdfStamper will generate the new PDF file
stamp.close();
} catch (Exception de) {
de.printStackTrace();
}
}
}
Solution 2: Show new changes
Here is my code snippet for refreshing the view after adding annotation, I have added this into AndroidPdfViewer core classes.
public void refresh(int currPage) {
currentPage = currPage;
if (!hasSize) {
waitingDocumentConfigurator = this;
return;
}
PDFView.this.recycle();
PDFView.this.callbacks.setOnLoadComplete(onLoadCompleteListener);
PDFView.this.callbacks.setOnError(onErrorListener);
PDFView.this.callbacks.setOnDraw(onDrawListener);
PDFView.this.callbacks.setOnDrawAll(onDrawAllListener);
PDFView.this.callbacks.setOnPageChange(onPageChangeListener);
PDFView.this.callbacks.setOnPageScroll(onPageScrollListener);
PDFView.this.callbacks.setOnRender(onRenderListener);
PDFView.this.callbacks.setOnTap(onTapListener);
PDFView.this.callbacks.setOnLongPress(onLongPressListener);
PDFView.this.callbacks.setOnPageError(onPageErrorListener);
PDFView.this.callbacks.setLinkHandler(linkHandler);
if (pageNumbers != null) {
PDFView.this.load(documentSource, password, pageNumbers);
} else {
PDFView.this.load(documentSource, password);
}
}
Solution 4: Click on object in pdf
I have create annotations and set it to added image object, AndroidPdfViewer has an event handler, here is the example
#Override
public void handleLinkEvent(LinkTapEvent event) {
// do your stuff here
}
I will add other new solutions into my question, as update parts.
Here is my code snippet for adding text into pdf file,
Your code does not add text into an existing pdf file. It creates a new PDF, adds text to it, and appends this new PDF to the existing file presumably already containing a PDF. The result is one file containing two PDFs.
Concatenating two files of the same type only seldom results in a valid file of that type. This does works for some textual formats (plain text, csv, ...) but hardly ever for binary formats, in particular not for PDFs.
Thus, your viewer gets to show a file which is invalid as a PDF, so your viewer could simply have displayed an error and quit. But PDF viewers are notorious for trying to repair the files they are given, each viewer in its own way. Thus, depending on the viewer you could also see either only the original file, only the new file, a combination of both, an empty file, or some other repair result.
So your observation,
but this will replace with all of the Pdf file, not just inserting into it
is not surprising but may well differ from viewer to viewer.
To actually change an existing file with OpenPDF (or any iText version before 6 or other library forked from such a version) you should read the existing PDF using a PdfReader, manipulate that reader in a PdfStamper, and close that stamper.
For example:
PdfReader reader = new PdfReader("original.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("original-stamped.pdf"));
PdfContentByte cb = stamper.getOverContent(1);
cb.beginText();
cb.setTextMatrix(100, 400);
cb.showText("Text at position 100,400.");
cb.endText();
stamper.close();
reader.close();
In particular take care to use different file names here. After closing the stamper and the reader you can delete the original PDF and replace it with the stamped version.
If it is not desired to have a second file, you can alternatively initialize the PdfStamper with a ByteArrayOutputStream and after closing the stamper and the reader replace the contents of the original file with those of the ByteArrayOutputStream.
I want to convert text to docx format in android app .I want to know how I could achieve the same.
I tried directly converting from text to docx first.
I tried implementing Apache POI and Aspose library but I didn't find my solution. Aspose library on runtime gave error of "Duplicate API ", I checked Aspose forum it is not resolved yet .I tried whatever it is told.
I tried implementing text to pdf it is done.
Now I want to know how to convert from pdf to docx?
Can anybody help with proper functioning details to achieve this task ? or any other suggestion so that text to docx can be converted?
// Below code is for converting directly from text to docx .
// This is using Apache POI but it is not importing classes after adding library
private void docxFormat()
{
XWPFDocument xwpfDocument = new XWPFDocument();
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(new File("yourfilepath/filename.docx"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
for(String s:lines) {
XWPFParagraph xwpfParagraph = xwpfDocument.createParagraph();
XWPFRun xwpfRun = xwpfParagraph.createRun();
xwpfRun.setText(s);
}
xwpfDocument.write(fileOutputStream);
fileOutputStream.close();
}
// Anybody any suggestion for converting text to docx
You can easily convert a Text file to Word formats such as DOC, DOCX, RTF and to many other formats (PDF, XPS, HTML etc) by using the following Aspose.Words for Android via Java API's code:
try
{
String licString = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Aspose.Words.Android.lic";
String inputPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/input.txt";
String outputPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/output.docx";
com.aspose.words.License lic = new com.aspose.words.License();
lic.setLicense(licString, this);
com.aspose.words.Document doc = new com.aspose.words.Document(inputPath);
doc.save(outputPath);
}
catch (Exception e)
{
e.printStackTrace();
}
Hope, this helps. I work with Aspose as Developer Evangelist.
I have a 300 page PDF file. I want to create a new PDF file from my chosen pages the existing pdf file.
I have created a blank PDF File (using PDFBox ) like this:
// Create a new empty document
PDDocument document = new PDDocument();
// Create a new blank page and add it to the document
PDPage blankPage = new PDPage();
document.addPage( blankPage );
// Save the newly created document
document.save("BlankPage.pdf");
and this is how I am reading a page from pdf File.
PDDocument doc = PDDocument.load("Hello World.pdf");
PDPage firstPage = (PDPage) doc.getDocumentCatalog().getAllPages().get(67);
My question is, how do I get the contents of 'firstpage' into "blankPage.pdf".
If I can choose the x,y coordinates of the firstpage(where it is to be overlayed), it would be even better.
P.S.
The page sizes of my Hello World file are not A4.Each page is more like a thumbnail with text and shapes.So, overlaying is possible on A4. Also, I do not want to convert the files to image and then onverlay, I want the whole pdf file to be pasted as is(without converting to image first)
it turns out that iText can do the same thing.Here is the code for that :
PdfReader reader = new PdfReader("Hello World.pdf");
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream("RESULT.PDF"));
document.open();
PdfContentByte canvas = writer.getDirectContent();
PdfImportedPage page;
for (int i = 3; i <=6; i++) {
page = writer.getImportedPage(reader, i);
canvas.addTemplate(page, 1f, 0, 0, 1, 0, i*30-250);
}
document.close();
I am trying to create a custom keyboard and use "SoftKeyboard" sample in android SDK for it. I did few modifications with that sample and created my custom keyboard. I can use this custome keyboard with default Messaging app of my Android device.
Now I want to click a button in my custom keyboard and add an image when I type a SMS. I noticed that there is String Builder in "SoftKeyBoard.java" class (private StringBuilder mComposing = new StringBuilder()) and it is appended chars when we type letters using keyboard.
I tried to append an image of my SD card like below,
String imageDataString = "";
String path = Environment.getExternalStorageDirectory().toString() + "/SamplePictures/";
File file = new File(path, "myimage.jpg");
try {
FileInputStream imageInFile = new FileInputStream(file);
byte imageData[] = new byte[(int) file.length()];
imageInFile.read(imageData);
// Converting Image byte array into Base64 String
imageDataString = encodeImage(imageData);
imageInFile.close();
} catch (FileNotFoundException e) {
System.out.println("Image not found" + e);
} catch (IOException ioe) {
System.out.println("Exception while reading the Image " + ioe);
}
and I appended "imageDataString" to String builder like below,
mComposing.append(imageDataString);
But I got so many characters, not an image.
Is it possible to insert an image when I type SMS using my keyboard?
Updated : I used ImageSpan and Spannable with following code.
SpannableStringBuilder ssb = new SpannableStringBuilder( "Here's a my picture " );
Bitmap smiley = BitmapFactory.decodeResource( getResources(), R.drawable.bitmap );
ssb.setSpan( new ImageSpan( smiley ), 16, 17,Spannable.SPAN_INCLUSIVE_INCLUSIVE );
mComposing.append(ssb);
But it displays only "Here's a my picture" and no image. I created a sample separate app with an EditText and set above "ssb" variable as the text of that EditText. Then it displays well the image. But it doesn't work with Messaging app. If I can set the Messaging app EditText, I guess I can set the image.
Is there any way to access and update the Edit text of Messaging app?
Thanks in Advance..!!
I think what you want to do is use an ImageSpan added to a Spannable, a solution which is already described here. After pressing the image button on your keyboard, you'll fire of a method that should update the editText by taking the existing text from it, adding an ImageSpan containing your image and setting that back to the editText.
I have a Sqlite database in Android and I want to display its content in a PDF file, by building it dynamically in Android on pressing a Button.
I am aware with iText but I want to go with a simpler solution..
Can anyone help me with it plz!!
Look at droidtext which a port of the iText library version 2.1.7 for Android.
There are lots of examples too. Get started with Helloworld.
public class HelloWorld {
/**
* Generates a PDF file with the text 'Hello World'
*
* #param args
* no arguments needed here
*/
public static void main(String[] args) {
System.out.println("Hello World");
// step 1: creation of a document-object
Document document = new Document();
try {
// step 2:
// we create a writer that listens to the document
// and directs a PDF-stream to a file
PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + "droidtext" + java.io.File.separator + "HelloWorld.pdf"));
// step 3: we open the document
document.open();
// step 4: we add a paragraph to the document
document.add(new Paragraph("Hello World"));
} catch (DocumentException de) {
System.err.println(de.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
// step 5: we close the document
document.close();
}
}
For display content of Sqlite database into pdf you have to use itextpdf-5.2.1.jar.you can download it from here
Example code:
DatabaseHandlerofdatabase dbHandler = new DatabaseHandlerofdatabase(this);
SQLiteDatabase db = dbHandler.getWritableDatabase();
Cursor c1 = db.rawQuery("SELECT * FROM tablename", null);
String filename="nameoffile.pdf";
Document document=new Document(); // create the document
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs(); // create root directory in sdcard
}
File gpxfile = new File(root,filename); // generate pdf file in that directory
PdfWriter.getInstance(document,new FileOutputStream(gpxfile));
document.open(); // open the directory
Paragraph p3=new Paragraph(); // to enter value you have to create paragraph and add value in it then paragraph is added into document
p3.add("Username : ");
document.add(p3);
// now for ad table in pdf use below code
PdfPTable table = new PdfPTable(3); // Code 1
// Code 2
table.addCell("CATEGORY");
table.addCell("BUDGET");
table.addCell("USED BUDGET");
// now fetch data from database and display it in pdf
while (c1.moveToNext()) {
// get the value from database
String ex_bdgt = c1.getString(3);
String used_bdgt = c1.getString(5);
table.addCell(type);
table.addCell(ex_bdgt);
table.addCell(used_bdgt);
int temp_ex=Integer.parseInt(ex_bdgt);
ttlbud=ttlbud+temp_ex;
int temp_used=Integer.parseInt(used_bdgt);
usdbud=usdbud+temp_used;
}
// add table into document
document.add(table);
document.addCreationDate();
document.close();
I have tried Ketul Patel solution, the solution is fine in principle, but I needed to change few things in it. I changed the way I created the file in the directory, I got the idea from here, and it worked perfectly. and my final code is:
The DatabaseHelper is a class I created in my project which extends SQLiteOpenHelper. read more
public void createPdf() throws FileNotFoundException, DocumentException {
String dir = Environment.getExternalStorageDirectory()+File.separator+"myLogs";
File folder = new File(dir);
folder.mkdirs();
File file = new File(dir, "LogHistory.pdf");
Cursor c1 = database.rawQuery("SELECT * FROM " + DatabaseHelper.TABLE_LOG, null);
Document document = new Document(); // create the document
PdfWriter.getInstance(document, new FileOutputStream(file));
document.open();
Paragraph p3 = new Paragraph();
p3.add("Your Log History for \n");
document.add(p3);
PdfPTable table = new PdfPTable(4);
table.addCell("Date");
table.addCell("Start");
table.addCell("End");
table.addCell("Total");
while (c1.moveToNext()) {
String date = c1.getString(3);
String start = c1.getString(1);
String end = c1.getString(2);
String total = c1.getString(4);
table.addCell(date);
table.addCell(start);
table.addCell(end);
table.addCell(total);
}
document.add(table);
document.addCreationDate();
document.close();
}
I have completed the PDF implementation in php with the help of fpdf Tutorials. With this I also got help for Pie Charts and Bar Charts for graphical representation in my pdf. Also this format simplifies for mailing our pdf file as an attachment as it could be stored as various ways.