I am trying to create a pdf file and save it to sd card. I searched for solutions to my problem but what i found in the net was about creating and saving a file or image. But neither solves my problem. Here's my sample code:
public void createPdf(){
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStoragePublicDirectory("DIRECTORY_PDF") + java.io.File.separator + "droidtext" + java.io.File.separator + "HelloWorld"));
document.open();
document.add(new Paragraph("Hello World"));
} catch (DocumentException de) {
System.err.println(de.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
document.close();
and here's what the logcat says:
02-21 06:28:08.001: W/System.err(859): /mnt/sdcard/DIRECTORY_PDF/droidtext/HelloWorld: open failed: ENOENT (No such file or directory)
Related
when I use docx4j to generate doc from HTML and output through java servlet, it works well on Windows system, I can download and open the doc file normally.
When I put the project on Linux server, I can also download the doc file, but when openging file, it alert that the file is broken. I must click the confirm and restore the file.then open it normally.
my core code is like this.
how can i get the same result as windows?
code in jsp:
String vhtml = DownHtml2DocUtil.replaceSvgData2Base64(request);
response.reset();
response.setContentType("application/octet-stream");//设置为字节流
OutputStream output = null;
try {
output = response.getOutputStream();
response.addHeader("Content-Disposition", "attachment;filename=" + System.currentTimeMillis() + ".doc");
DownHtml2DocUtil.genDocFromHtml(vhtml, output);
} catch (Exception e) {
} finally {
try {
if (output != null) {
output.close();
}
} catch (Exception e) {
}
}
response.flushBuffer();
out.clear();
out = pageContext.pushBody();
code in java like this:
public static void genDocFromHtml(String html, OutputStream out)
throws EMPException {
try {
WordprocessingMLPackage wordMLPackage;
wordMLPackage = WordprocessingMLPackage.createPackage();
XHTMLImporterImpl XHTMLImporter = new XHTMLImporterImpl(
wordMLPackage);
wordMLPackage.getMainDocumentPart().getContent()
.addAll(XHTMLImporter.convert(html, "utf-8"));
// wordMLPackage.save(out); -- i tried both method
new Save(wordMLPackage).save(out);
} catch (InvalidFormatException e) {
throw new EMPException(e);
} catch (Docx4JException e) {
throw new EMPException(e);
} catch (Exception e) {
e.printStackTrace();
}
}
any suggestion will be appreciate , thanks anyway;
I have been trying to write PDF files on android ,when i am using internal storage it shows no error but i am unable to see the file created and if i change path to external storage i get permission denied even though i have given permission in my manifest file.
I have creating a class which i am calling from activity to write files it fetches data from database.
Here is the code.
public boolean createPdfFile(String path, Employee employee,String month,Context context){
boolean status=false;
if(path!=null && employee!=null){
Document document=new Document();
try{
if(!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
Toast.makeText(this, "External SD card not mounted", Toast.LENGTH_LONG).show();
}
File sdCard=Environment.getExternalStorageDirectory();
File file=new File(sdCard,month+"_"+employee.getEmployeeName()+".pdf");
PdfWriter writer=PdfWriter.getInstance(document,new FileOutputStream(file));
writer.setEncryption(employee.getDateOfBirth().getBytes(),employee.getEmployeeName().getBytes(), PdfWriter.ALLOW_PRINTING,PdfWriter.ENCRYPTION_AES_128);
document.open();
Paragraph p=new Paragraph();
p.add("Payslip for the month of January");
p.setFont(new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD, new BaseColor(1, 1, 1)));
p.setAlignment(Element.ALIGN_CENTER);
document.add(p);
PdfPTable table=new PdfPTable(2);
table.setWidthPercentage(100); //Width 100%
table.setSpacingBefore(10f); //Space before table
table.setSpacingAfter(10f); //Space after table
float[] columnWidths = {1.5f, 1.5f};
table.setWidths(columnWidths);
table.addCell("Employee Code");
table.addCell(employee.getEmployeeID());
table.addCell("Department");
table.addCell(employee.getDepartment().getDepartmentName());
table.addCell("Date of Birth");
table.addCell(employee.getDateOfBirth());
table.addCell("Date of Joining");
table.addCell(employee.getDateOfJoining());
table.addCell("Employee Name");
table.addCell(employee.getEmployeeName());
document.add(table);
document.close();
writer.close();
status=true;
}catch (FileNotFoundException e) {
status=false;
Log.e("PDF exception aaa",e.getMessage());
}catch (DocumentException e) {
status=false;
Log.e("PDF exception abc",e.getMessage());
} catch (IOException e) {
status=false;
Log.e("PDF exception",e.getMessage());
}
}
return status;
}
If you are developing for API level 23 or newer you need to explicitly ask the user for permission.
See: https://developer.android.com/training/permissions/requesting.html#perm-check
I am trying to make password protected PDF file which is already created in my directory .
Below is my sample code:
try {
PdfReader pdfReader = new PdfReader("D:/test/SI1491232250299.pdf");
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream("D:/test/SI1491232250299.pdf"));
pdfStamper.setEncryption("abc".getBytes(), "abc".getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
pdfStamper.close();
} catch (Exception e) {
e.printStackTrace();
}
After execution got java.io.EOFException exception
I have a problem saving a file in android, the FileOutputStream keeps falling back to a FileNotFoundException and thus won't write the file to the external storage.
Yes I do have permission set in the manifest:
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
I've added the code below of the function, can someone explain to me what is going wrong, if it is that it is trying to overwrite an existing file, is there a way to replace that file (the name needs to be static)?
(tips on making the code look nicer are welcome as well)
Bitmap savebitmap = Bitmap.createBitmap(drawView.getDrawingCache());
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Files");
if (!mediaStorageDir.exists()){
mediaStorageDir.mkdir();
}
File pictureFile = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Files"+File.separator+"Tempsave.png");
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
savebitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
}
catch (FileNotFoundException e) {}
catch (IOException e) {}
Kudos to Guillaume and theV0ID for leading me to the most efficient correct answer.
Below is the example code editted to the working version.
Bitmap savebitmap = Bitmap.createBitmap(drawView.getDrawingCache());
File pictureFile = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Files"+File.separator+"Tempsave.png");
pictureFile.getParentFile().mkdirs();
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
savebitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
}
catch (FileNotFoundException e) {}
catch (IOException e) {}
Try this :
File pictureFile = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Files"+ File.separator + "Tempsave.png");
pictureFile.getParentFile().mkdirs();
You need to create the file directories if they don't exist. If not the FileOutputStream will throw a FileNotFoundException
I'm trying to insert an image in an existing PDF file but iText puts it on the first page and I'm losing the rest of the page content. How can I insert it without losing existing content?
I used this code:
public static void main(String[] args) {
Document document = new Document(PageSize.A4);
try {
PdfWriter.getInstance(document, new FileOutputStream(
"/home/amira/work/APPS-579/word/generatedMergedDocs/FinalTest/1.pdf"));
document.open();
Image image = Image.getInstance(
"/home/amira/work/APPS-579/word/generatedMergedDocs/FinalTest/a.jpg");
document.add(image);
} catch (DocumentException de) {
de.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
document.close();
}
You're adding the image to an empty document, because you're not reading the original document, just overwriting it.
To modify an existing document with itext with an image, please see the following tutorial which explains it perfectly.