I am building a Java web service application in which I would like to convert the HTML file to PDF and send an email to a particular email address.
Conversion from XHTML to PDF.
try {
File outputFile = new File("D:\\Files\\Output_Files\\" + System.currentTimeMillis() + ".pdf");
OutputStream file = new FileOutputStream(outputFile);
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, file);
document.open();
InputStream is = new ByteArrayInputStream(htmlString.getBytes());
XMLWorkerHelper.getInstance().parseXHtml(writer, document,is);
document.close();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
I have verified htmlString and it holds an exact HTML string.
Please review my HTML content here
The issue is that I am receiving the PDF but it does not have any content but an empty page.
Related
I am exploring usage of iText maven dependency to generate a pdf from the below code.
try {
Document document = new Document();
OutputStream outputStream =
new FileOutputStream(new File("C:\\ImageTester\\samplePDF.pdf"));
PdfWriter.getInstance(document, outputStream);
//Open the document
document.open();
document.add(new Paragraph("Hello world ");
//Close document and outputStream.
document.close();
outputStream.close();
System.out.println("Pdf created successfully.");
} catch (Exception e) {
e.printStackTrace();
}
Maven:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>
This above works fine and generate the PDF. However, I have a use-case where I am sent Base64 encoded String that needs to be saved as PDF. How do I this? Converting the Base64 to a byte array and writing that to the outputStream generates the a corrupted PDF.
byte[] bytes = Base64.getDecoder().decode(b64String);
outputStream.write(bytes);
PdfWriter.getInstance(document, outputStream);
I am using itextpdf-5.5.4 jar to merge or add two pdf into one PDF.
I did not get any error or exception while running code but displayed below text in Merged PDF. I did not get below text when i open individual PDF's.
The document you are trying to load requires Adobe Reader 8 or higher.
You may not have the Adobe Reader installed or your viewing
environment may not be properly configured to use Adobe Reader.
For information on how to install Adobe Reader and configure your
viewing environment please see
http://www.adobe.com/go/pdf_forms_configure.
void mergePdfFiles(List<InputStream> inputPdfList, OutputStream outputStream) throws Exception {
// Create document and pdfReader objects.
Document document = new Document();
List<PdfReader> readers = new ArrayList<PdfReader>();
int totalPages = 0;
// Create pdf Iterator object using inputPdfList.
Iterator<InputStream> pdfIterator = inputPdfList.iterator();
// Create reader list for the input pdf files.
while (pdfIterator.hasNext()) {
InputStream pdf = pdfIterator.next();
PdfReader pdfReader = new PdfReader(pdf);
readers.add(pdfReader);
totalPages = totalPages + pdfReader.getNumberOfPages();
}
// Create writer for the outputStream
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
// Open document.
document.open();
// Contain the pdf data.
PdfContentByte pageContentByte = writer.getDirectContent();
PdfImportedPage pdfImportedPage;
int currentPdfReaderPage = 1;
Iterator<PdfReader> iteratorPDFReader = readers.iterator();
// Iterate and process the reader list.
while (iteratorPDFReader.hasNext()) {
PdfReader pdfReader = iteratorPDFReader.next();
// Create page and add content.
while (currentPdfReaderPage <= pdfReader.getNumberOfPages()) {
document.newPage();
pdfImportedPage = writer.getImportedPage(pdfReader, currentPdfReaderPage);
pageContentByte.addTemplate(pdfImportedPage, 0, 0);
currentPdfReaderPage++;
}
currentPdfReaderPage = 1;
}
// Close document and outputStream.
outputStream.flush();
document.close();
outputStream.close();
System.out.println("Pdf files merged successfully.");
}
public static void main(String args[]) {
try {
List<InputStream> inputPdfList = new ArrayList<InputStream>();
inputPdfList.add(new FileInputStream("pdf1.pdf"));
inputPdfList.add(new FileInputStream("pdf2.pdf"));
OutputStream outputStream = new FileOutputStream("Merge-PDF.pdf");
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
mergePdfFiles(inputPdfList, byteStream);
byte[] byteS = byteStream.toByteArray();
outputStream.write(byteS);
} catch (Exception e) {
e.printStackTrace();
}
}
Please help me out on this.
I have an html file, which is generated as a response by my site.
While opening the html file in my browser, all the images and other elements are displaying properly. Moreover, I want to convert this html file into a pdf file.
So am using iText API to generate the pdf file.
In the html file images and texts are located horizontally.
But in the generated pdf output the images are displaying vertically.
code
String k = convertString();
OutputStream file = new FileOutputStream(new File("f:\\Test.pdf"));
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, file);
document.open();
InputStream is = new ByteArrayInputStream(k.getBytes());
XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
document.close();
file.close();
private static String convertString() {
StringBuilder contentBuilder = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new FileReader("f://testPage.html"));
String str;
while ((str = in.readLine()) != null) {
contentBuilder.append(str);
}
in.close();
} catch (IOException e) {
}
String content = contentBuilder.toString();
return content;
}
How can I generate a pdf that looks exactly the same as the appearance of the html UI?
Also, in Jfiddle, the html page is not displaying properly. What am I missing? Is the problem with my HTML, or is there some deeper issue with Jfiddle or something else at work?
String w=request.getParameter("fpath");
try {
FileReader fr = new FileReader(w);
BufferedReader reader = new BufferedReader(fr);
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line.trim());
}
String result = sb.toString();
OutputStream file = new FileOutputStream(new File("E:\\Test.pdf"));
Document document = new Document();
PdfWriter.getInstance(document, file);
document.open();
#SuppressWarnings("deprecation")
HTMLWorker htmlWorker = new HTMLWorker(document);
htmlWorker.parse(new StringReader(result));
response.addHeader("Content-Disposition", "attachment; filename=\"file.pdf\"");
response.setContentType("application/pdf");
document.close();
file.flush();
}
catch (Exception e) {
e.printStackTrace();
}
This is My code to save html to Pdf file But when I click On save as Button it save to E:\Test.pdf ,while I don't want to set E:\Test.pdf Physical path I want that if user will click On save Button then it should ask where u need to save if user will select that location Then it save to that place response.addHeader("Content-Disposition", "attachment; filename=\"file.pdf\"");
response.setContentType("application/pdf"); I dont know how to set file name and file content to this so that i can able to save my pdf file to desire location.
So, instead of creating a new FileOutputStream use the response.getOutputStream(). Apart from setting the headers you are not sending anything else in the response
i want to save the generated pdf file inside my project folder ,
using this code . I have generated it successfully and want to save
it in my project folder , where the jsp file exist ,Below is my code
<%# page import="java.servlet.*,
javax.servlet.http.*,
java.io.*,
java.util.*,
com.itextpdf.text.pdf.*,
com.itextpdf.text.*,java.sql.*" %><%
response.setContentType("application/pdf"); Document document = new
Document(); try{
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
PdfWriter.getInstance(document, buffer);
document.open();
PdfPTable table = new PdfPTable(2);
table.addCell("1");
table.addCell("2");
table.addCell("3");
table.addCell("4");
table.addCell("5");
table.addCell("6");
document.add(table);
document.close();
DataOutput dataOutput = new DataOutputStream(response.getOutputStream());
byte[] bytes = buffer.toByteArray();
response.setContentLength(bytes.length);
for(int i = 0; i < bytes.length; i++)
{
dataOutput.writeByte(bytes[i]);
}
}catch(DocumentException e){
e.printStackTrace(); }
%>
thanks in advance..
Use getServletContext().getRealPath(..)