PDFView fill pdf form - java

I try to fill pdf form. I open and load pdf file by PDFView but how I can fill pdf form?
I try to do this:
File file = new File("/storage/emulated/0/test/ankieta.pdf");
PDFView pdfView = (PDFView) findViewById(R.id.pdfView);
if (file.exists()) {
pdfView.fromFile(file)
.enableSwipe(true) // allows to block changing pages using swipe
.swipeHorizontal(false)
.enableDoubletap(true)
.password(null)
.scrollHandle(null)
.enableAntialiasing(true) // improve rendering a little bit on low-res screens
.spacing(0)
.autoSpacing(false) // add dynamic spacing to fit each page on its own on the screen
.pageSnap(true) // snap pages to screen boundaries
.pageFling(false) // make a fling change only a single page like ViewPager
.nightMode(false)
.onTap(new OnTapListener() {
#Override
public boolean onTap(MotionEvent e) {
return false;
}
})
.load();
}

First make your pdf to editable pdf.
using this site:-https://www.jotform.com/fillable-pdf-form-creator/
in this site generate a field id and save it any where because using this id you can fill pdf of fix postion of pdf and generated pdf save in res->raw->yourpdf
Now write this code
reader = new PdfReader(current.getResources().openRawResource(R.raw.form));
and using this code you can add in pdf
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(file, false));
AcroFields acroFields = stamper.getAcroFields();
acroFields.setField("name", "Hardik Talaviya");
acroFields.setField("enroll", "150040116022");
acroFields.setField("branch", "IT");
acroFields.setField("sem", "8");
stamper.setFormFlattening(true);
stamper.close();
Here name,enroll,branch and sem is my pdf id which can generated when you create editable pdf.
And last save this pdf in your storage it is fill and open it where you want to open.
I hope this can help you!
Thank You.

Another service that can help you fill in a PDF.
www useanvil.com/developers
They have APIs for filling, generating and signing PDFs. The documentation seems pretty good and there is a prewritten node client.

Related

How to export a PDF from WebView where I can select text, inside the new PDF

I'm trying to convert WebView's text content to PDF. Using the code below.
PdfDocument.Page page = document.StartPage(new PdfDocument.PageInfo.Builder(webpage.Width, webpage.Height, 1).Create());
webpage.Draw(page.Canvas);
PDF is properly generated but I can't select text from that PDF. Its like WebView content but converted into an image.
But if I try to print same WebView from the print menu and save it as PDF text selection is working and size of the pdf is smaller.
So how can I create PDF from WebView where text is also selectable.
Eg. of text selection.
What you did is printing the web page as an image to the PDF canvas - that's why the size is larger, and you cannot select text. Because the text is not present there as a text object, but as an image.
The reason for this, is that you draw the webview (and not the webpage) to the PDF canvas. That is just like outputting the view itself as a bitmap to the PDF.
What you might want to do is to use an XHTML to PDF rendering library, like iText or Flying Saucer to properly render the XHTML webpage (and not the webview!) to a PDF.
You can use iText library for this, add this dependency in gradle
compile 'com.itextpdf:itextg:5.5.10'
Now convert the webview's text to pdf like this
try {
File mFolder = new File(getExternalFilesDir(null) + "/sample");
File imgFile = new File(mFolder.getAbsolutePath() + "/Test.pdf");
if (!mFolder.exists()) {
mFolder.mkdir();
}
if (!imgFile.exists()) {
imgFile.createNewFile();
}
String webviewText = "<html><body>Your webview's text content </body></html>";
OutputStream file = new FileOutputStream(imgFile);
Document document = new Document();
PdfWriter.getInstance(document, file);
document.open();
HTMLWorker htmlWorker = new HTMLWorker(document);
htmlWorker.parse(new StringReader(webviewText));
document.close();
file.close();
} catch (Exception e) {
e.printStackTrace();
}

iText generated dynamic pdf printing blank page

I have a dynamic pdf form , which is filled programatically from xml input data by using iText APIs. But when we print the filled dynamic pdf form, blank page is printed. If we open and save the output pdf and then print, its working fine.
Can anybody help why would be the reason for blank page and how this issue can be resolved?
My form filling code:
PdfReader reader=new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader,new FileOutputStream(dest),'\0', true);
PdfWriter writer=stamper.getWriter();
File file = new File(src);
String fileName=file.getName();
PdfAction action = null;
action = PdfAction.javaScript(readJsFileTostring(jsFileName), writer);
writer.setOpenAction(action);
stamper.setPageAction(PdfWriter.PAGE_OPEN, action, 1);
AcroFields form = stamper.getAcroFields();
XfaForm xfa = form.getXfa();
xfa.fillXfaForm(new FileInputStream(xmlData));
stamper.close();
I use Adobe Acrobat Reader DC 2018.009.20050 to print the form.

How to copy/move AcroForm fields from one document to new blank one using IText5 or IText7?

I need to copy whole AcroForm including field positions and values from template PDF to a new blank PDF file. How can I do that?
In short words - I need to get rid of "background" from the template and leave only filed forms.
The whole point of this is to create a PDF with content that would be printed on pre-printed templates.
I am using IText 5 but I can switch to 7 if usefull examples would be provided
After a lot of trial and error I have found the solution to "How to copy AcfroForm fields into another PDF". It is a iText v7 version. I hope it will help somebody someday.
private byte[] copyFormElements(byte[] sourceTemplate) throws IOException {
PdfReader completeReader = new PdfReader(new ByteArrayInputStream(sourceTemplate));
PdfDocument completeDoc = new PdfDocument(completeReader);
ByteArrayOutputStream out = new ByteArrayOutputStream();
PdfWriter offsetWriter = new PdfWriter(out);
PdfDocument offsetDoc = new PdfDocument(offsetWriter);
offsetDoc.initializeOutlines();
PdfPage blank = offsetDoc.addNewPage();
PdfAcroForm originalForm = PdfAcroForm.getAcroForm(completeDoc, false);
// originalForm.getPdfObject().copyTo(offsetDoc,false);
PdfAcroForm offsetForm = PdfAcroForm.getAcroForm(offsetDoc, true);
for (String name : originalForm.getFormFields().keySet()) {
PdfFormField field = originalForm.getField(name);
PdfDictionary copied = field.getPdfObject().copyTo(offsetDoc, false);
PdfFormField copiedField = PdfFormField.makeFormField(copied, offsetDoc);
offsetForm.addField(copiedField, blank);
}
offsetDoc.close();
completeDoc.close();
return out.toByteArray();
}
Did you check the PdfCopyForms object:
Allows you to add one (or more) existing PDF document(s) to create a new PDF and add the form of another PDF document to this new PDF.
I didn't find an example, but you could try something like this:
PdfReader reader1 = new PdfReader(src1); // a document with a form
PdfReader reader2 = new PdfReader(src2); // a document without a form
PdfCopyForms copy = new PdfCopyForms(new FileOutputStream(dest));
copy.AddDocument(reader1); // add the document without the form
copy.CopyDocumentFields(reader2); // add the fields of the document with the form
copy.close();
reader1.close();
reader2.close();
I see that the class is deprecated. I'm not sure of that's because iText 7 makes it much easier to do this, or if it's because there were technical problems with the class.

How to add text watermark to pdf in Java using Apache PDFBox?

I am not getting any tutorial for adding a text watermark in a PDF file? Can you all please guide me, I am very new to PDFBOX.
Its not duplicate, the link in the comment didn't help me. I want to add text, not an image to the pdf.
Here is an example using PDFBox 2.0.2. This will load a PDF and write some text in the bottom right corner in a red transparent font. If it is a multiple page PDF the watermark will appear on every page. It might not be production ready, as I am not sure if there are some additional null conditions that need to be checked, but it should get you running in the right direction.
Keep in mind that this particular block of code will not modify the original PDF, but will create a new PDF using the Tmp_(filename) as the output.
private static void watermarkPDF (File fileStored) {
File tmpPDF;
PDDocument doc;
tmpPDF = new File(fileStored.getParent() + System.getProperty("file.separator") +"Tmp_"+fileStored.getName());
doc = PDDocument.load(fileStored);
for(PDPage page:doc.getPages()){
PDPageContentStream cs = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true);
String ts = "Some sample text";
PDFont font = PDType1Font.HELVETICA_BOLD;
float fontSize = 14.0f;
PDResources resources = page.getResources();
PDExtendedGraphicsState r0 = new PDExtendedGraphicsState();
r0.setNonStrokingAlphaConstant(0.5f);
cs.setGraphicsStateParameters(r0);
cs.setNonStrokingColor(255,0,0);//Red
cs.beginText();
cs.setFont(font, fontSize);
cs.setTextMatrix(Matrix.getTranslateInstance(0f,0f));
cs.showText(ts);
cs.endText();
}
cs.close();
}
doc.save(tmpPDF);
}

Why does portrait page changes to landscape page after inserting pdf using iText?

Am using "itext-5.5.8", trying to insert (one) page of portrait pdf into a main pdf document, code works perfect but after inserting portrait pages automatically changes to landscape pages, don't know why?
CODE:
try {
PdfReader firstPdf = new PdfReader(mainFileWithPath); //main doc
PdfReader secondPdf =new PdfReader(addFileNameWithPath); // inserting pages
PdfStamper stamp = new PdfStamper(firstPdf, new FileOutputStream(outputPDFFile));
int totalNumOfPagesToInsert = secondPdf.getNumberOfPages();
int i =1;
while (i<=totalNumOfPagesToInsert) {
// Get a page(s) from secondPdf with the given pageNo
PdfImportedPage page = stamp.getImportedPage(secondPdf,i);
// insert new page in to the newly created pdf at specified page number.
stamp.insertPage(INSERT_AT_PAGE_NO + (i-1), secondPdf.getPageSize(i));
// copy the content of the page copied from secondPdf.
stamp.getUnderContent(INSERT_AT_PAGE_NO + (i-1)).addTemplate(page, 0, 0);
i++;
}
//close the new created pdf.
stamp.close();
Please give me directions to fix this! Thanks
As Author #Bruno Lowagie mentioned that "didn't take into account that rotation"
Have fixed the issue like ... Code Below ...
try {
PdfReader firstPdf = new PdfReader(mainFileWithPath);
PdfReader secondPdf =new PdfReader(addFileNameWithPath);
// create new pdf with the content from firstPdf
PdfStamper stamp = new PdfStamper(firstPdf, new FileOutputStream(outputPDFFile));
stamp.setRotateContents(false);
int totalNumOfPagesToInsert = secondPdf.getNumberOfPages();
int i =1;
while (i<=totalNumOfPagesToInsert) {
// Get a single page from secondPdf with the given pageNo
PdfImportedPage page = stamp.getImportedPage(secondPdf,i); //Actual working code
// insert new page in to the newly created pdf at specified page number.
// choose page size bas
stamp.insertPage(INSERT_AT_PAGE_NO + (i-1), secondPdf.getPageSizeWithRotation(i)); //Actual working code
// copy the content of the page copied from secondPdf.
stamp.getUnderContent(INSERT_AT_PAGE_NO + (i-1)).addTemplate(page, 0, 0); //Actual working code
i++;
}
//close the new created pdf.
stamp.close();

Categories

Resources