I want to protect a .doc file with password using apache poi. I am getting this error while running code. please help me
Exception in thread "main"
org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException: The
supplied data appears to be in the OLE2 Format. You are calling the
part of POI that deals with OOXML (Office Open XML) Documents. You
need to call a different part of POI to process this data (eg HSSF
instead of XSSF) at
org.apache.poi.openxml4j.opc.internal.ZipHelper.verifyZipHeader(ZipHelper.java:179)
at
org.apache.poi.openxml4j.opc.internal.ZipHelper.openZipFile(ZipHelper.java:237)
at
org.apache.poi.openxml4j.opc.ZipPackage.(ZipPackage.java:134)
at
org.apache.poi.openxml4j.opc.ZipPackage.(ZipPackage.java:117)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:257)
POIFSFileSystem fs=new POIFSFileSystem();
EncryptionInfo info=new EncryptionInfo(EncryptionMode.agile);
Encryptor enc=info.getEncryptor();
enc.confirmPassword("user");
OPCPackage opc=OPCPackage.open("D:/Amar.doc", PackageAccess.READ_WRITE);
OutputStream os=enc.getDataStream(fs);
opc.save(os);
opc.close();
FileOutputStream stream=new FileOutputStream("D:/ao.doc");
fs.writeFilesystem(stream);
stream.close();
System.out.println("running");
I checked and reference to Apache POI documentation, it says that the password encryption for .doc file support since version 3.17, so I give it a try.
It must use HWPFDocument instead to open your doc file.
Then you need to set password by:
Biff8EncryptionKey.setCurrentUserPassword(password);
Complete method:
public static void encryptDocFile(File inputDocFile, File outputDocFile, String password) {
try {
FileInputStream fileInput = new FileInputStream(inputDocFile);
BufferedInputStream bufferInput = new BufferedInputStream(fileInput);
POIFSFileSystem poiFileSystem = new POIFSFileSystem(bufferInput);
// Setting password
Biff8EncryptionKey.setCurrentUserPassword(password);
HWPFDocument wordDoc = new HWPFDocument(poiFileSystem);
FileOutputStream fileOut = new FileOutputStream(outputDocFile);
wordDoc.write(fileOut);
bufferInput.close();
fileOut.close();
wordDoc.close();
System.out.println("Encrypted successfully");
} catch (IOException e) {
System.out.println("Failed to encrypt doc file");
e.printStackTrace();
}
}
Or you can checkout the complete code here:
If you have further question or feedback, please let me know. Thank you
Related
I have create Rest Service and I am trying to Generate Zip file. This Zip file created from muliple PDF files which are downloaded using method InputStream inpuStream = new URL(url).openStream() . I am able to Generate Zip file Which included PDF files but PDF files are broken.
Even If i try to Generate it from String its coming as broken PDF and i am getting Error message "Not a supported File Type or file is broken or damaged". Its simple code but seems like i am unable to track the mistake.
I have provided my controller , service method for your reference.
1)Controller:
#GetMapping("/getZipFile")
public void getZipFile(HttpServletResponse response) throws RestException {
try {
ByteArrayOutputStream baos = generateZipService.getZipFile();
ServletOutputStream responseOutPutStream = response.getOutputStream();
response.setContentType("APPLICATION/OCTET-STREAM");
response.setStatus(HttpServletResponse.SC_OK);
response.addHeader("Content-Disposition", "attachment; filename=\"GeneratedZipFile.zip\"");
responseOutPutStream.write(baos.toByteArray());
responseOutPutStream.flush();
} catch (Exception e) {
throw new RestException("Error In downloading Zip File");
}
}
2)Service Method
public ByteArrayOutputStream getZipFile() throws Exception{
List<ZipFileName> zipFileNames= zipFileNameDao.getZipFileName();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zipOut= new ZipOutputStream(baos);
for (String fileName : zipFileNames) {
InputStream inpuStream = new ByteArrayInputStream( "this is test to generarte pdf test file this is test tdfsfs this is test to generarte pdf test file this is test tdfsfs".getBytes(Charsets.UTF_8) );
createZipFile(inpuStream,zipOut,fileName);
inpuStream.close();
}
zipOut.flush();
baos.flush();
zipOut.close();
baos.close();
return baos;
}
3)createzipfile from service method :
```private void createZipFile(InputStream inputStream, ZipOutputStream zipOut,String fileName) throws IOException {
ZipEntry zipEntry = new ZipEntry(fileName+".pdf");
BufferedInputStream bis = new BufferedInputStream(inputStream);
zipOut.putNextEntry(zipEntry);
zipOut.write(IOUtils.toByteArray(inputStream));
zipOut.closeEntry();
bis.close();
inputStream.close();
}
Also , Another question is about using channels. I read channels are better when you have large files to downlaod from server . I have less then 20 kb of file so should I use Java.nio or just Zipoutputstream is fine.
I try with "response.setContentType("APPLICATION/ZIP")" but it didnt change the outcome of the project.
Thank you for your help..
The code worked fine only thing missing was to pass authentication with the openStream() method because of which I was getting the broken PDF. I opened the pdf with notepad++ and found the error ..
I resolved it.
Thank you
When I try to create a workbook from an already existing xls received as an InputStream using apache poi 4.1.2:
InputStream inputStream = new ByteArrayInputStream(input);
Workbook workbook = null;
try {
workbook = WorkbookFactory.create(inputStream);
} catch (IOException e) {
...
}
I received the following exception: "Caused by: java.lang.IndexOutOfBoundsException: Unable to read 512 bytes from 328192 in stream of length 328192"
If I open the xls file and just save it before uploaded it again, it works fine.
I am implementing AES Algorithm 128 bit key. After encryption, the first 16 bytes of encrypted data will be stored in a .docx file. After that the .docx file will be blocked.
XWPFDocument document = new XWPFDocument() ;
FileOutputStream out = new FileOutputStream(filename,true);//filename is .docx word document
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText(ress1);//ress1 is a String datatype
document.write(out);
As per what I understand from your comment, you want to encrypt your word file. You can achieve that using following code snippet:
POIFSFileSystem fs = new POIFSFileSystem();
EncryptionInfo info = new EncryptionInfo(fs, EncryptionMode.agile);
Encryptor enc = info.getEncryptor();
enc.confirmPassword(<your_password>);
OPCPackage opc = OPCPackage.open(new File(<file_path>), PackageAccess.READ_WRITE); //opening package for encryption
OutputStream os = enc.getDataStream(fs); //perform encryption
opc.save(os); //save package
opc.close();
FileOutputStream fos = new FileOutputStream("file_path");
fs.writeFilesystem(fos); //write the file back to file system
fos.close();
I am working in a project which is already developed. Now I have a task to generate excel file using Apache poi API.
My problem is I have PrinWriter object available instead of OutputStream.
workbook.write(outputStream);
How to tackle this situation?
File f=new File("c://newfolder//lijo.xls");
PrintWriter out=new PrintWriter(f);
FileOutputStream fout=new FileOutputStream(f);
for converting from one output stream to another just pass the reference value
example to convert file to fileoutput stream
File file=new File("c://lijo.xls");
FileOutputStream outputStream=new FileOutputStream(file);
If you work on web project you may use ServletOutputStream and doing something like this
Workbook wb = new HSSFWorkbook();
ServletOutputStream out = response.getOutputStream();
wb.write(out);
out.flush();
out.close();
Or you can use FileInputStream
Workbook wb = WorkbookFactory.create(new FileInputStream("MyExcel.xlsx"));
5i need to convert a HSSFWorkbook (Apache's POI) to an ByteArray and later to convert the ByteArray back to the HSSFWorkbook. The following TestCase illustrates my problem:
#Test
public void testXLSExportImport(){
try {
InputStream is = new FileInputStream(FILEPATH);
HSSFWorkbook wb = new HSSFWorkbook(is);
byte[] exported = wb.getBytes();
HSSFWorkbook wb2 = new HSSFWorkbook(new ByteArrayInputStream(exported));
//in the line above the exception is thrown
} catch (Exception e) {
assertTrue(false);
}
}
the testcase fails with the exception: java.io.IOException: Invalid header signature; read 0x0005060000100809, expected 0xE11AB1A1E011CFD0
(I am using Apaches POI 3.5-beta3)
I hope somebody can help me... how can I get it work?!
You're not writing the workbook correctly! You need to use the write(Outputstream) call.
As shown in the various examples on the website, your code should instead be:
InputStream is = new FileInputStream(FILEPATH);
HSSFWorkbook wb = new HSSFWorkbook(is);
ByteArrayOutputStream out = new ByteArrayOutputStream();
wb.write(out);
HSSFWorkbook wb2 = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray()));
Also, don't open a Workbook from a FileInputStream, if you have a File use that directly. Opening from a File uses less memory than from a Stream.