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();
Related
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.
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 made an app in android studio (Java) on which is possible to fill some brief data in text boxes. Also app has two buttons, one for loading image from gallery and one for saving complete data to pdf.
I can successfully save all text data, but have problem with loaded image. Image is sucessfully loaded to app, but i dont know hot to save it to pdf. Image is loaded as an ImageView object.
Just to mention for pdf part i use itext.
Pls, help with hints or code for saving ImageVIew object to pdf file.
i had the same problem, but i can fixed.
first i changed the way i used to pick the image and replaced it with this code:
Intent getImage = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(getImage, GALLERY_REQUEST_CODE);
then, in the class onActivityResult i transformed the uri to a bitmap using this:
if(requestCode==GALLERY_REQUEST_CODE && resultCode== RESULT_OK && data!=null){
Uri imageData = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(imageData,filePath,null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePath[0]);
String myPath = cursor.getString(columnIndex);
cursor.close();
Bitmap bitmap = BitmapFactory.decodeFile(myPath);
then passed the bitmap to the pdf
pdf.addFoto(bitmap);
and finally, in the pdf template i used this to put the image in a table:
public void addFoto (Bitmap u) {
try{
PdfPTable tabla = new PdfPTable(1);
tabla.setWidthPercentage(60);
tabla.setSpacingBefore(10);
tabla.setSpacingAfter(10);
Bitmap bmp = u;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image image = Image.getInstance(stream.toByteArray());
PdfPCell imageCell = new PdfPCell();
imageCell.addElement(image);
tabla.addCell(imageCell);
document.add(tabla);
Look into PdfDocument
Example from the documentation
// create a new document
PdfDocument document = new PdfDocument();
// crate a page description
PageInfo pageInfo = new PageInfo.Builder(new Rect(0, 0, 100, 100), 1).create();
// start a page
Page page = document.startPage(pageInfo);
// draw something on the page
View content = getContentView();
content.draw(page.getCanvas());
// finish the page
document.finishPage(page);
. . .
// add more pages
. . .
// write the document content
document.writeTo(getOutputStream());
// close the document
document.close();
I am designing a speech-to-text android application where I display the converted text in a textview. I want to save the converted text in the form of a word file/pdf on the user's device. Can somebody tell me how to do it. Thanks.
To create a .pdf file
// create a new document
PdfDocument document = new PdfDocument();
// crate a page description
PageInfo pageInfo = new PageInfo.Builder(new Rect(0, 0, 100, 100), 1).create();
// start a page
Page page = document.startPage(pageInfo);
// draw something on the page
View content = getContentView();
content.draw(page.getCanvas());
// finish the page
document.finishPage(page);
. . .
// add more pages
. . .
// write the document content
document.writeTo(getOutputStream());
// close the document
document.close();
for more detail please have a look on below link:
https://developer.android.com/reference/android/graphics/pdf/PdfDocument.html
I hope, it will work.
I want to read a pdf file using Java/Android from my SD card. I imported the itextpdf5.1.1.jar file in to Eclipse. I am able to read a file if I create a new file from an existing one, like this:
public void readPdfFile(String pFilename){
try{
Document document = null;
document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(OUTPUTFILE));
document.open();
PdfReader reader = new PdfReader(pFilename);
int n = reader.getNumberOfPages();
PdfImportedPage page;
// Go through all pages
for (int i = 1; i <= n; i++) {
// Only page number 2 will be included
if (i == 1) {
page = writer.getImportedPage(reader, i);
Image instance = Image.getInstance(page);
document.add(instance);
}
}
}
catch (DocumentException e) {
// TODO: handle exception
System.out.println("Doc Exception"+ e);
}
catch (IOException io) {
// TODO: handle exception
System.out.println("IO Exception"+ io);
}
}
But I want to read the file without creating a new pdf file in my sd card. How can I do this?
Please guide me how to create a pdf reader application in Android that reads the pdf file and also allows you to enter a page number to jump to.
It is impossible to replace an existing PDF. We can able to write or manipulate anything in our PDF but it could not be replaced with the original. While using iText we can make change and save it in a new file and not in a original file, this information is available in the iText official website.
You can use awt tools like jPanel in java with iText to read a pdf file.
In Android there is a pdf viewer for reading or viewing pdf files.