Create a Word file using POI - java

My requirement is that I should read a template file and change some values in its content and write it back to another file. Most importantly it should have the same styles as that of the template.
The problem I face is that I am able to read and write, but its very difficult to transfer the styles as well. Especially I am tired trying to apply the paragraph styles to the document. Pls help me..... this is my code
public static void main(String[] args) {
try {
HWPFDocument templateFile = new HWPFDocument(new FileInputStream("D:\\POI\\testPOIin.doc"));
HWPFDocument blankFile = new HWPFDocument(new FileInputStream("D:\\POI\\blank.doc"));
ParagraphProperties pp = templateFile.getRange().getParagraph(4).cloneProperties();
blankFile.getRange().insertAfter(pp, 0);
OutputStream out = new FileOutputStream("D:\\POI\\testPOIout.doc");
blankFile.write(out);
} catch (FileNotFoundException fnfe) {
// TODO: Add catch code
fnfe.printStackTrace();
} catch (Exception ioe) {
// TODO: Add catch code
ioe.printStackTrace();
}
}
}
Pls let me know that I am doing wrong.....

I also had similar task and after investigation i created solution, but it works only for docx files:
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream(new File("transformed.docx"));
XWPFDocument doc = new XWPFDocument(new FileInputStream(new File("original.docx")));
for(XWPFParagraph p:doc.getParagraphs()){
for(XWPFRun r:p.getRuns()){
for(CTText ct:r.getCTR().getTList()){
String str = ct.getStringValue();
if(str.contains("NAME")){
str = str.replace("NAME", "Java Dev");
ct.setStringValue(str);
}
}
}
}
doc.write(fos);
}
it operates on low level elements so it saves styles and other props. Hope it will help somebody.

Related

Reading and writing object array list to text file

public void readList () {
try {
FileOutputStream writeData = new FileOutputStream("Accounts.txt");
ObjectOutputStream writeStream = new ObjectOutputStream(writeData);
writeStream.writeObject(AccountCredentials);
writeStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
public void writeList() {
try {
FileInputStream readData = new FileInputStream("Accounts.txt");
ObjectInputStream readStream = new ObjectInputStream(readData);
AccountCredentials = (ArrayList <Accounts>) readStream.readObject();
readStream.close();
System.out.println(AccountCredentials.size());
}
catch (Exception e) {
e.printStackTrace();
}
}
My readList method works fine right, I have ¬í sr java.util.ArrayListxÒ™Ça I sizexp w
in the file. My writeList does not. I have a School folder inside the Netbeans folder, and in the main directory is Accounts.txt. Do I need to specify that? My Java file is in Schools/src. It always says my list size is 0
Can you please share the exception or stack trace you are getting and paste it here ? , Also I would highly recommend not to use a flat file for storing the account credentials, rather use any of the identity management solution and db driven account management. Did you also try to debug the following line "ObjectInputStream readStream = new ObjectInputStream(readData);"

FileoutputStream FileNotFoundException

I'm using java SE eclipse.
As I know, When there are no file named by parameter FileOutputStream constructor create new file named by parameter. However, with proceeding I see that FileOutputStream make exception FileNotFoundException. I really don't know Why this exception needed. Anything wrong with my knowledge?
My code is following(make WorkBook and write into file. In this code, although there are no file "data.xlsx", FileOutpuStream make file "data.xlsx".
public ExcelData() {
try {
fileIn = new FileInputStream("data.xlsx");
try {
wb = WorkbookFactory.create(fileIn);
sheet1 = wb.getSheet(Constant.SHEET1_NAME);
sheet2 = wb.getSheet(Constant.SHEET2_NAME);
} catch (EncryptedDocumentException | InvalidFormatException | IOException e) {
e.printStackTrace();
} // if there is file, copy data into workbook
} catch (FileNotFoundException e1) {
initWb();
try {
fileOut = new FileOutputStream("data.xlsx");
wb.write(fileOut);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} // if there is not file, create init workbook
} // ExcelData()
If anything weird, please let me know, thank you
It will throw a FileNotFoundException if the file doesn't exist and cannot be created (doc), but it will create it if it can. To be sure you probably should first test that the file exists before you create the FileOutputStream (and create with createNewFile() if it doesn't)
File yourFile = new File("score.txt");
yourFile.createNewFile();
FileOutputStream oFile = new FileOutputStream(yourFile, false);
Answer from here: Java FileOutputStream Create File if not exists
There is another case, where new FileOutputStream("...") throws a FileNotFoundException, i.e. on Windows, when the file is existing, but file attribute hidden is set.
Here, there is no way out, but resetting the hidden attribute before opening the file stream, like
Files.setAttribute(yourFile.toPath(), "dos:hidden", false);

Transferring data from input to output File, getting Exception

My data is not getting transferred to the output file , I always get an Exception.
import java.io.*;
import java.util.*;
class TransferData {
public static void main(String[] args) {
String path1="E:\\IO\\Input.txt";
String path2="E:\\IO\\Output.txt";
int data;
System.out.println("Transfering started...");
try {
FileInputStream fis=new FileInputStream(path1);
FileOutputStream fos=new FileOutputStream(path2);
while((data=fis.read())!=-1) {
fos.write(data);
}
}
catch(Exception e) {
System.out.println("exception caught!");
}
System.out.println("Completed...");
}
}
How do I transfer data to output file ?
Tested this code on my local machine it is works without exceptions.
Check is file E:/IO/Input.txt exists.
IS Directory E:/IO is writeable for your user
(If file E:/IO/Output.txt already exists check is it writeable and not opened in another programm)
By code:
It is good practice to close FIS and FOS after programm finished execution.
public class TransferData {
public static void main(String[] args) {
String path1 = "E:\\IO\\Input.txt";
String path2 = "E:\\IO\\Output.txt";
int data;
System.out.println("Transfering started...");
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(path1);
fos = new FileOutputStream(path2);
while ((data = fis.read()) != -1) {
fos.write(data);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("Completed...");
}
}
If you replace System.out.println("exception caught!"); with e.printStackTrace(); then you will get a much more useful error message.
If you then post that error message here, people will be able to help you much more easily.
It could be the case that the program cannot find the file you're trying to read.
I highly suggest to use e.printStackTrace() as the others suggested.
One possible problem might be the filesystem permissions or the file you are trying to read from being not existent.
You might also want to use a "try with resources" to simplify your code.
Your code is missing a close statement for your Streams too.
All together your code would look something like this:
import java.io.*;
import java.util.*;
class TransferData {
public static void main(String[] args) {
String path1="E:\\IO\\Input.txt";
String path2="E:\\IO\\Output.txt";
int data;
System.out.println("Transfering started...");
try (
FileInputStream fis=new FileInputStream(path1);
FileOutputStream fos=new FileOutputStream(path2)
) {
while((data=fis.read())!=-1) {
fos.write(data);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
One last thing, if you post your code on StackOverflow, please do not mix different formatting styles (e.g. { in the same line as an if and sometimes in the next) and try to have the code well formatted from the beginning.
Add e.printStackTrace() to your catch block, and post the data printed in your console here, people will be able to help you better.
The most likely cause of the exception getting thrown is that the system is not able to find the file "E:\\IO\\Input.txt" or "E:\\IO\\Output.txt" make sure that the file's are there and Output.txt is not set to read only.

Give password protection to existing pdf file

Am trying to give password to an existing pdf file. It is working for a jasper report which is saved with .jrxml or .jasper but how to give it for pdf file.
Sample code:
public static void main(String[] args) {
String USER="Sai123";
String OWNER="Sairam";
try {
InputStream input=new FileInputStream(new File("D:\\Project1\\EmailSendExample\\WebContent\\PDFiles\\AnnexI.pdf"));
OutputStream file = new FileOutputStream(new File("D:\\Test.pdf"));
/*PdfReader reader = new PdfReader(input);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("D:\\Test.pdf"));
stamper.setEncryption(PdfWriter.ALLOW_PRINTING, OWNER,USER, PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA);
stamper.close();
reader.close();*/
JRPdfExporter exporter = new JRPdfExporter();
//exporter.setParameter(JRExporterParameter.INPUT_FILE, new File("D:\\Project1\\EmailSendExample\\WebContent\\PDFiles\\AnnexI.pdf"));
exporter.setParameter(JRExporterParameter.OUTPUT_FILE,new File("D:\\Test.pdf"));
exporter.setParameter(JRPdfExporterParameter.OWNER_PASSWORD, "Sai123");
exporter.setParameter(JRPdfExporterParameter.USER_PASSWORD, "Sairam");
exporter.setParameter(JRPdfExporterParameter.IS_ENCRYPTED, Boolean.TRUE);
exporter.exportReport();
System.out.println("Report Generation Complete");
file.close();
} catch (Exception e) {
e.printStackTrace();
}
it is throwing error like
net.sf.jasperreports.engine.JRException: No input source supplied to the exporter.
at net.sf.jasperreports.engine.JRAbstractExporter.setInput(JRAbstractExporter.java:922)
at net.sf.jasperreports.engine.export.JRPdfExporter.exportReport(JRPdfExporter.java:296)
at pdfpassword.main(pdfpassword.java:45)
Thanks in advance for your valuable suggestions.
According to me,we cannot provide pdf file as input to JRexporter. so in order to make existing pdf password protected use the code below.It works for me.
code:
private static String USER_PASSWORD = "password";
private static String OWNER_PASSWORD = "naveen";
public static void main(String[] args) throws IOException {
try
{
PdfReader pdfReader = new PdfReader("/home/base/Desktop/newtask/ext.pdf");
PdfStamper pdfStamper = new PdfStamper(pdfReader,new FileOutputStream("/home/base/Desktop/newtask/ext1.pdf"));
pdfStamper.setEncryption(USER_PASSWORD.getBytes(),OWNER_PASSWORD.getBytes(), PdfWriter.ALLOW_PRINTING,PdfWriter.ENCRYPTION_AES_128);
pdfStamper.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (com.itextpdf.text.DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I see this line commented -
//exporter.setParameter(JRExporterParameter.INPUT_FILE, new File("D:\\Project1\\EmailSendExample\\WebContent\\PDFiles\\AnnexI.pdf"));
And exception talks about input -
net.sf.jasperreports.engine.JRException: No input source supplied to the exporter.

How to check if a PDF is Password Protected or not

I am trying to use iText's PdfReader to check if a given PDF file is password protected or not, but am getting this exception:
Exception in thread "Main Thread" java.lang.NoClassDefFoundError:org/bouncycastle/asn1/ASN1OctetString
But when testing the same code against a non-password protected file it runs fine. Here is the complete code:
try {
PdfReader pdf = new PdfReader("C:\\abc.pdf");
} catch (IOException e) {
e.printStackTrace();
}
In the old version of PDFBox
try
{
InputStream fis = new ByteArrayInputStream(pdfBytes);
PDDocument doc = PDDocument.load(fis);
if(doc.isEncrypted())
{
//Then the pdf file is encrypeted.
}
}
In the newer version of PDFBox (e.g. 2.0.4)
InputStream fis = new ByteArrayInputStream(pdfBytes);
boolean encrypted = false;
try {
PDDocument doc = PDDocument.load(fis);
if(doc.isEncrypted())
encrypted=true;
doc.close();
}
catch(InvalidPasswordException e) {
encrypted = true;
}
return encrypted;
Use Apache PDFBox - Java PDF Library from here:Sample Code:
try
{
document = PDDocument.load( "C:\\abc.pdf");
if(document.isEncrypted())
{
//Then the pdf file is encrypeted.
}
}
The way I do it is by attempting to read the PDF file using PdfReader without passing a password of course. If the file is password protected, a BadPasswordException will be thrown. This is using the iText library.
Here's a solution that doesn't require 3rd party libraries, using the PdfRenderer API.
fun checkIfPdfIsPasswordProtected(uri: Uri, contentResolver: ContentResolver): Boolean {
val parcelFileDescriptor = contentResolver.openFileDescriptor(uri, "r")
?: return false
return try {
PdfRenderer(parcelFileDescriptor)
false
} catch (securityException: SecurityException) {
true
}
}
Reference: https://developer.android.com/reference/android/graphics/pdf/PdfRenderer
try {
PdfReader pdfReader = new PdfReader(String.valueOf(file));
pdfReader.isEncrypted();
} catch (IOException e) {
e.printStackTrace();
}
Using iText PDF library you can check. If it went to an exception handle it(ask for password)
Try this code:
boolean isProtected = true;
PDDocument pdfDocument = null;
try
{
pdfDocument = PDDocument.load(new File("your file path"));
isProtected = false;
}
catch(Exception e){
LOG.error("Error while loading file : ",e);
}
Syste.out.println(isProtected);
If your document is password protected then it can not load document and throw IOException.
Verified above code using pdfbox-2.0.4.jar
public boolean checkPdfEncrypted(InputStream fis) throws IOException {
boolean encrypted = false;
try {
PDDocument doc = PDDocument.load(fis);
if (doc.isEncrypted())
encrypted = true;
doc.close();
} catch (
IOException e) {
encrypted = true;
}
return encrypted;
}
Note: There is one corner case in iText some file are encrypted protected but open without a password, to read those files and add water mark like this
PdfReader reader = new PdfReader(src);
reader.setUnethicalReading(true);
I didn't want to use any third party library, so i used this -
try {
new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));
} catch (Exception e) {
e.printStackTrace();
// file is password protected
}
If the file was password protected, i didn't use it.

Categories