I tried to make PDF with itext 7.2.1, this is my code:
try{
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Kegiatan/" + eventName + ".pdf";
File file = new File(path);
file.mkdirs();
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document document = new Document(pdfDoc, new PageSize(612, 936).rotate());
document.setMargins(0,0,0,0);
//Title
Paragraph paragraph = new Paragraph();
paragraph.add(new Text(eventName).setFontSize(14).setTextAlignment(TextAlignment.CENTER).setBold());
document.add(paragraph);
document.close();
}
catch (IOException e) {
e.printStackTrace();
}
I got this error message, pointing at document.close()
java.lang.ExceptionInInitializerError
How i can fix this?
Related
File Name = new File("G:/Java/lesson25_1/Name.txt");
if(Name==null){
JOptionPane.showMessageDialog(this, "Details are missing");
}
try{
FileReader fr1 = new FileReader("Name.txt");
BufferedReader br1=new BufferedReader(fr1);
String str=br1.readLine();
br1.close();
when i do this in a method it dosn't work when i click the button
There is a method for file called exists to check if the given file exist or not.
String path = "G:/Java/lesson25_1/Name.txt";
File file = new File(path);
if(!file.isFile() || !file.canRead()){
JOptionPane.showMessageDialog(this, "Details are missing");
} else {
try {
FileReader fr1 = new FileReader("Name.txt");
BufferedReader br1=new BufferedReader(fr1);
String str=br1.readLine();
br1.close();
} catch (Exception e){
e.printStackTrace();
}
}
What I am trying to do is add a new page to the end of the current pdf that I am editing right after setFields() method. I am getting it with PdfReader and never have a Document object so I am not sure how I would do this. Here are the two methods that are creating the PDF.
Edit :
Upon further investigation I found that you can insert a page with stamper.insertPage. But This seems to be a little too hard to do what I want with it. Is there a way to just merge two pdf's with acrofields together? And by merge I mean the first pdf have 2 pages and the second pdf have 1 page and put them together and now the pdf has 3 pages.
public static void createPdf(MyDocument document) {
try {
PdfReader pdfTemplate = initPdfReader();
if (pdfTemplate != null) {
OutputStream output = FacesContext.getCurrentInstance().getExternalContext().getResponseOutputStream();
PdfStamper stamper = new PdfStamper(pdfTemplate, output);
stamper.setFormFlattening(true);
AcroFields fields = stamper.getAcroFields();
setFields(document, fields, stamper);
stamper.close();
FacesContext.getCurrentInstance().responseComplete();
}
} catch (Exception e) {
BeanUtils.addMessage(new Message("An error has occurred while crating PDF.:" + ExceptionUtils.getStackTrace(e)));
LOG.error(e);
}
}
InitPdfReader()
public static PdfReader initPdfReader() throws Exception {
PdfReader pdfReader = null;
InputStream inStream = null;
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.responseReset();
ec.setResponseContentType("pdf");
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + "FileName" + "\"");
inStream = FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/resources/documents/MyDocument.pdf");
pdfReader = new PdfReader(inStream);
pdfReader.close();
} finally {
if (inStream != null) {
inStream.close();
}
}
return pdfReader;
}
I have a Word document, where I have to replace text and save this document in Oracle database, in PDF format. Have someone any idea how to resolve this?
String inputFilename = "/root/GeneratorUmow/web/WEB-INF/umowy/kkb/wniosekozaciag.docx";
try(InputStream is = new FileInputStream(inputFilename)) {
dbd = new DokumentyBlobDAO();
db.setNazwaPliku("Wniosek_o_zaciagniecie.pdf");
db.setTypDokuemntu(876990);
if(du.getTypKlienta() == S_ID_Lead_Partner_Typ_Klienta_KKB) {
POIFSFileSystem fs = null;
fs = new POIFSFileSystem(is);
HWPFDocument doc = new HWPFDocument(fs); //funkcja zamyka inputstream
Range range = doc.getRange();
range.replaceText("my&&nazwa&&firmy", "KAKAOWY SZATAN");
//konwersja na pdf
FileOutputStream fos = new FileOutputStream(pathToDirectory + File.separator + folderName+File.separator + "wniosekzaciagniecie.docx");
doc.write(fos);
String inputChangeFile = pathToDirectory+ File.separator +folderName+File.separator+"wniosekzaciagniecie.docx";
InputStream inputstream = new FileInputStream(inputFilename);
length = inputChangeFile.length();
System.out.println("dlugosc lancucha " + length);
XWPFDocument document = new XWPFDocument(inputstream);
System.out.println("message3");
PdfOptions options = PdfOptions.create();
PdfOptions options = PdfOptions.create().fontEncoding("windows-1250");
System.out.println("message4");
OutputStream out = new FileOutputStream(new File(pathToDirectory+ File.separator +folderName+File.separator+"kakaowyszal.pdf"));
PdfConverter.getInstance().convert(document, out, options);
System.out.println("message5");
}
}
catch( Exception ex){
System.out.println("err" + ex);
return -1;
}
one of my junior code is not sending excel file as attachment . It is sending file like
------=_Part_0_2066339629.1374147892060
Content-Type: text/plain; name="Service_Change_Alert_Thu Jul 18 17:14:50 IST 2013.xlsx"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="Service_Change_Alert_Thu Jul 18 17:14:50 IST 2013.xlsx"
UEsDBBQACAAIANqJ8kIAAAAAAAAAAAAAAAARAAAAZG9jUHJvcHMvY29yZS54bWytkV1LwzAUhu/7
K0Lu2yTr1BHaDlEGguLADsW7kB7bYvNBEu3892bdrCheennyPu/D4aRY79WA3sH53ugSs4xiBFqa
ptdtiXf1Jl3hdZUkhTQOts5YcKEHj2JL+xJ3IVhOiJcdKOGzGOuYvBinRIija4kV8lW0QBaUnhMF
QTQiCHKwpXbW4aOPS/vvykbOSvvmhknQSAIDKNDBE5Yx8s0GcMr/WZiSmdz7fqbGcczGfOLiRow8
3d0+TMunvfZBaAm4ShAqTnYuHYgADYoOHj4slPgrecyvrusNrhaU5Sm9SNmqZowvl/yMPhfkV//k
function is following
public void sendSeviceabilityMail(List<OctpinSaveBean> datalist)
throws MessagingException {
Session session = null;
Map<String, String> utilsMap = ApplicationBean.utilsProperties;
if (utilsMap == null || utilsMap.size() == 0)
utilsMap = ApplicationBean.getUtilsPropertyFileValues();
smtpHost = utilsMap.get("SMTPHost");
to = utilsMap.get("To");
try {
if (smtpHost != null && to != null) {
Date date = new Date();
XSSFWorkbook updateDataBook =
updatedServiceabilityExcel(datalist);
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpHost);
props.put("To", to);
session = Session.getInstance(props, null);
String str = "strstr";
Multipart multipart = new MimeMultipart();
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setContent(str, "text/html");
BodyPart messageBodyPart = new MimeBodyPart();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
updateDataBook.write(baos);
byte[] bytes = baos.toByteArray();
DataSource ds = new ByteArrayDataSource(bytes,
"application/vnd.ms-excel");
DataHandler dh = new DataHandler(ds);
messageBodyPart.setDataHandler(dh);
String fileName = "Service_Change_Alert_" + date+".xlsx";
messageBodyPart.setFileName(fileName);
messageBodyPart.setHeader("Content-disposition", "attachment;
filename=\"" + fileName + "\"");
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart);
if (to != null && to.length() > 0) {
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("tech_noida
<tech_noida#xyz.com>"));
String[] toArray = to.split(",");
InternetAddress[] address = new
InternetAddress[toArray.length];
for (int i = 0; i < toArray.length; i++) {
address[i] = new InternetAddress(toArray[i]);
}
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("Updated Serviceability Alert!!!");
msg.setContent(multipart);
msg.setSentDate(date);
try {
Transport.send(msg);
logger.info("Mail has been sent about the updated serviceability alert to :" + to);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
The problem is not related to POI, but with JavaMail (plus the way different email clients handles the specs and malformed emails). Try this:
Multipart multipart = new MimeMultipart();
MimeBodyPart html = new MimeBodyPart();
// Use actual html not "strstr"
html.setContent("<html><body><h1>Hi</h1></body></html>", "text/html");
multipart.addBodyPart(html);
// ...
// Joop Eggen suggestion to avoid spaces in the file name
String fileName = "Service_Change_Alert_"
+ new SimpleDateFormat("yyyy-MM-dd_HH:mm").format(date) + ".xlsx";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
updateDataBook.write(baos);
byte[] poiBytes = baos.toByteArray();
// Can be followed by the DataSource / DataHandler stuff if you really need it
MimeBodyPart attachment = new MimeBodyPart();
attachment.setFileName(filename);
attachment.setContent(poiBytes, "application/vnd.ms-excel");
//attachment.setDataHandler(dh);
attachment.setDisposition(MimeBodyPart.ATTACHMENT);
multipart.addBodyPart(attachment);
Update:
Also don't forget to call saveChanges to update the headers before sending the message.
msg.saveChanges();
See this answer for further details.
I had a part of code which suppose to get an image from website and store it into the sdcard. The following code was working find when i develop on sdk1.5. However, it was not working now after i change it to android sdk 2.0. This line got problem; FileOutputStream fos = new FileOutputStream(filepath + "/" + this.filename);
Here is the code that i have:
void downloadFile(String fileUrl) {
URL myFileUrl = null;
try {
myFileUrl = new URL(fileUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
String filepath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
FileOutputStream fos = new FileOutputStream(filepath + "/"
+ this.filename);
bmImg.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
Context context = this.getBaseContext();
new MediaScannerNotifier2(context, filepath + "/" + this.filename,
"image/jpeg");
// displaying download completion message
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Wallpaper Downloaded").setCancelable(false)
.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
btn_setwall.setEnabled(true);
btn_download.setEnabled(false);
}
});
AlertDialog alert = builder.create();
alert.show();
} catch (Exception e) {
Log.e("MyLog", e.toString());
}
}
The error occur in the 3rd catch. However, when i move this line
FileOutputStream fos = new
FileOutputStream(filepath + "/" +
this.filename);
to the 2nd try/catch, then it will occur in the 2nd catch.
Can please help me on this?
Maybe try getting rid of .getAbsolutePath()
This works for me on 2.2:
FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + fileName);