I've a requirement where user are going to fill lots of fields ( text field, check box, radio button ) on pdf form and they will mail us. I need to read each fields on pdf form and insert into oracle table.
Edit1: I'm trying following code, It generates pdf but when I double click it says "invalid format". What's wrong ?
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
public class pdfGentest{
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream("c:\\HelloWorld.pdf"));
document.open();
document.add(new Paragraph("Hello World"));
}
catch (DocumentException de) {
System.err.println(de.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
}
}
Fixed: Due to I've not closed the document..Adding document.close(); fixed the problem
You can use IText library to do that. Link =>http://itextpdf.com/
Sadly I don't have java code example for that as I am using iTextSharp library for C#.NET buts pretty straightforward.
You might want to check itextpdf.com/book/examples.php for examples. Also check the following link for some example on reading field values,
http://itext-general.2136553.n4.nabble.com/Problem-Reading-Interactive-Form-Values-Acro-Fields-from-PDF-using-iText-td2171900.html
You can use PDF Box api, which will support to extract the fields information more clearly.
Related
I am attempting to build an Android app as a convenience wrapper for editing an Excel spreadsheet. I am using the Apache POI to interface with Excel in Java, which should be able to edit an existing workbook. The spreadsheet has no fancy formatting and the editing just changes or adds numbers. I can successfully read and write data to file. However, when I open the file in Microsoft Excel (either on mobile or on PC after transferring the file), I receive the following error message:
We found a problem with some content in 'filename.xlsx'. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Yes.
If I click yes, it opens the file in Read-only mode. All the data is there, nothing is missing. However, to edit the file in Excel, I must save it to a different filename, which is rather inconvenient. While I could in-principle work around it (I shouldn't need to open the file in Excel often), it seems symptomatic of more serious problems.
I have a hunch it is tangentially related to this question, where Excel was suspicious of a file which had been edited by an "untrusted" program. However, unlike that question where the file was opened in Protected Mode, here Excel is implying that the file is somehow damaged. Perhaps the issue is in the metadata?
Below is a minimum working example. When the user clicks on a button the selectFile method is called. This uses the Storage Access Framework to obtain the URI of the .xlsx file I want to edit, which is an Excel spreadsheet I created in Excel to be blank except for a number in cell A1 in Sheet1. The file is stored locally on my device (although I get the same problem when it is on OneDrive, which is where I actually want the file). This URI is then passed to the doEverything method, which does the actual work of editing the Excel file. (It also updates a textView with ID textView_data, which displays the value found in cell A1. This shows that it is reading the data properly.)
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MainActivity extends AppCompatActivity {
private TextView mText;
/**
* Opens the given workbook, increments the cell by 1, then writes and closes it.
*
* #param uri URI of XLSX file
*/
private void doEverything(Uri uri) {
if (uri == null) {
return;
}
XSSFWorkbook wb = null;
// Open the workbook
try (InputStream inp = getContentResolver().openInputStream(uri)) {
wb = (XSSFWorkbook) WorkbookFactory.create(inp);
// Increment cell A1 by 1.
XSSFCell cell = wb.getSheetAt(0).getRow(0).getCell(0);
cell.setCellValue(cell.getNumericCellValue()+1);
// Write the value of the cell to the saved textView.
mText.setText(Double.toString(cell.getNumericCellValue()));
} catch (IOException e) {
e.printStackTrace();
}
if (wb != null) {
try (OutputStream fileOut = getContentResolver().openOutputStream(uri)) {
// Write to file.
wb.write(fileOut);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Record the various Views we'll need later
mText = findViewById(R.id.textView_data);
}
/**
* Asks the user to select a .xlsx file. Called when the user presses a button.
*/
public void selectFile(View view) {
// Open an .xlsx file
openDoc.launch(new String[]{"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
}
// GetContent creates an ActivityResultLauncher<String> to allow you to pass
// in the mime type you'd like to allow the user to select
ActivityResultLauncher<String[]> openDoc = registerForActivityResult(new ActivityResultContracts.OpenDocument(),
new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri uri) {
doEverything(uri);
}
});
}
I am using Apache POI version 5.2.3. I am using the Microsoft Excel mobile app (Version 1.0.1 (16.0.15629.20092), 2018) and Excel 365 on desktop (Version 2209), both of which give the same issue. My phone uses Android 12 with SDK 31.
How can I edit the file without Excel thinking the file is broken?
I am trying to create a pdf using itext java library like:
Where I create highlighter icon(the arrow sign) like:
Phrase ph=new Phrase("รค", FontFactory.getFont(FontFactory.ZAPFDINGBATS, 14f));
Now I want that all the text of the advertisement ie.
Now own a Farm Plot nr Jigani in 5yrs installment option #INR450/sqft
with 5acre Club House.www.goldeneraproperty.com M-9999999999
should automatically wrap around the icon which I created above using FontFactory.ZAPFDINGBATS.
However I am stuck here.Please could anyone help me resolve it.
I tried creating a table of one column and one cell and put the icon in that cell but it did not help as the text did not wrap around the table.
Please suggest how could i create a pdf where the text would automatically wrap around the icon.Thanks in Advance!!!
I have designed it to a similar state. Please use you own alignment, fonts, sizes, etc. inside you PDF file.
PFB the code for above design:
package com.itext_dummy;
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class Hello {
/** Path to the resulting PDF file. */
public static final String RESULT
= "src/hello.pdf";
public static void main(String[] args)
throws DocumentException, IOException {
new Hello().createPdf(RESULT);
}
public void createPdf(String filename)
throws DocumentException, IOException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(filename));
document.open();
Image img = Image.getInstance("src/Arrow.png");
img.scaleAbsolute(50f, 50f);
img.setAlignment(Image.LEFT | Image.TEXTWRAP);
document.add(img);
Paragraph para = new Paragraph();
para.add("Now own a Farm Plot nr Jigani in 5yrs installment option #INR450/sqft with 5acre Club House.www.goldeneraproperty.com M-99999999994444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444");
document.add(para);
document.close();
}
}
Please do your own alignment on image size and paragraph text sizes and alignments.
Also PFB the icon image that I used:
I used the image since, that is the only way the wrapping could be done.
PFB my result screenshot:
I am stuck at this now. I have checked almost every popular question on SO site regarding Java Print API to print HTML files (with third-party libraries such as Flying Saucer, iText, CSSBox, etc). But still couldn't get it worked at my end yet.
Here are the links of my previous questions:
https://stackoverflow.com/questions/28106757/java-print-api-prints-html-with-huge-size
How to print HTML and not the code using Java Print API?
Basically I am trying to print the HTML file that contains some CSS with <style> tag. This CSS has classes applied for <table> and <p> tags for example. I cannot change CSS code inside HTML as it should be viewed exactly with this style in browser.
Below is my program
import java.awt.print.PrinterException;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.HashPrintServiceAttributeSet;
import javax.print.attribute.PrintServiceAttributeSet;
import javax.print.attribute.standard.PrinterName;
import javax.swing.JEditorPane;
public class Print {
public static void main(String[] args) throws PrintException {
String printerName = "\\\\network-path\\myPrinter";
String fileName = "C:\\log\\myLog.html";
URL url = null;
try {
url = (new File(fileName)).toURI().toURL();
} catch (MalformedURLException e) {
e.printStackTrace();
}
JEditorPane editorPane = new JEditorPane();
editorPane.setEditable(false);
if (url != null) {
try {
editorPane.setPage(url);
} catch (IOException e) {
System.err.println("Attempted to read a bad URL: " + url);
}
} else {
System.err.println("Couldn't find file: " + fileName);
}
PrintServiceAttributeSet printServiceAttributeSet = new HashPrintServiceAttributeSet();
printServiceAttributeSet.add(new PrinterName(printerName, null));
PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, printServiceAttributeSet); // list of printers
PrintService printService = printServices[0];
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
Copies copies = new Copies(1);
pras.add(copies);
pras.add(OrientationRequested.PORTRAIT);
pras.add(MediaSizeName.ISO_A4);
try {
editorPane.print(null, null, false, printService, pras, false);
} catch (PrinterException e) {
throw new PrintException("Print error occurred:" + e.getMessage());
}
}
}
The problem is above code works and I get good print of the above HTML with proper CSS styling. But it just scales up. When the said HTML is opened in IE it looks different and when it is printed by the code what I get is different. I would prefer the print to be same as it is viewed in IE.
I also tried to get it done by passing SimpleDoc object to the printer. My printService supports below formats:
image/gif [B
image/gif java.io.InputStream
image/gif java.net.URL
image/jpeg [B
image/jpeg java.io.InputStream
image/jpeg java.net.URL
image/png [B
image/png java.io.InputStream
image/png java.net.URL
application/x-java-jvm-local-objectref java.awt.print.Pageable
application/x-java-jvm-local-objectref java.awt.print.Printable
application/octet-stream [B
application/octet-stream java.net.URL
application/octet-stream java.io.InputStream
But nothing works with SimpleDoc. I then tried converting HTML to .png using CSSBox. It works but for multipage HTML, generated image is shrunk and is not viewable for printing. With Flying Saucer and iText version 2.0.8 I get NoSuchMethodError. Also even if I get it worked (by compiling the source against the said iText version) the output is broken.
Can someone please help? I would prefer to stick to Java Print API than using any third-party. Am I missing something when using SimpleDoc object approach? What settings need to be set to print above HTML using SimpleDoc object and available printService formats.
Hi I would like to create an excel file from a java code, I put this code on eclipse but nothing happen
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.FileOutputStream;
public class TestPOI1 {
public static void main(String[] args) {
//create the new workbook
Workbook workbook = new HSSFWorkbook();
try {
//create the output stream to save the document on the hard drive
FileOutputStream output = new FileOutputStream("Test1.xls");
//write the file onto the hard drive
workbook.write(output);
//finish it up by closing the document
output.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
in the console, this message is written
Usage: BiffDrawingToXml [options] inputWorkbook Options:
-exclude-workbook exclude workbook-level records
-sheet-indexes output sheets with specified indexes
-sheet-namek output sheets with specified name
and I can't found my excel file in the hard drive or in the file project. thanks for help.
Actually this error you will get while the Jar is still building. Just wait for few seconds.
Right Click and then Run : It will work..!
I want to convert several .jpg files (taken using the device camera) to ONE .pdf file.
I saw a lot of tools like iText, mupdf, PDFjet, pdjBox.
Is there something more simple? (like an API ready for android?)
Thanks.
using iText Library to convert the text to pdf. Use this to convert image to pdf.
import java.io.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
public class imagesPDF
{
public static void main(String arg[])throws Exception
{
Document document=new Document();
PdfWriter.getInstance(document,new FileOutputStream("YourPDFHere.pdf"));
document.open();
Image image = Image.getInstance ("yourImageHere.jpg");
document.add(new Paragraph("Your Heading for the Image Goes Here"));
document.add(image);
document.close();
}
}