i text jsp output to pdf [duplicate] - itext

This question already has answers here:
iText - generating files on the fly without needing a PDF file
(3 answers)
Closed 6 years ago.
i m trying to use the itext to convert the jsp output to pdf format
using itext and i dnt have much knowledge in java i m just starting the
programming please help me to convert the jsp output to pdf
i had tried some one example but its converting the jsp code to pdf but not the jsp out put
here is my code
import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileOutputStream;
public class PDFConversion
{
private void createPdf(String inputFile, String outputFile, boolean isPictureFile)
{
Rectangle pageSize = new Rectangle(2780, 2525);
Document pdfDocument = new Document(pageSize);
String pdfFilePath = "C:\\Users\\hp\\Desktop\\jsp_to_pdf.pdf";
try
{
FileOutputStream fileOutputStream = new FileOutputStream(pdfFilePath);
//PdfWriter writer = null;
PdfWriter writer = PdfWriter.getInstance(pdfDocument, fileOutputStream);
writer.open();
pdfDocument.open();
if (isPictureFile)
{
pdfDocument.add(com.lowagie.text.Image.getInstance("C:\\Users\\hp\\Documents\\NetBeansProjects\\pdf_print\\web\\example1.jsp"));
}
else
{
File file = new File("C:\\Users\\hp\\Documents\\NetBeansProjects\\pdf_print\\web\\example1.jsp");
pdfDocument.add(new Paragraph(org.apache.commons.io.FileUtils.readFileToString(file)));
}
pdfDocument.close();
writer.close();
}
catch (Exception exception)
{
System.out.println("Document Exception!" + exception);
}
}
public static void main(String args[])
{
PDFConversion pdfConversion = new PDFConversion();
pdfConversion.createPdf("example1.jsp","jsp_to_pdf.pdf", false);
}
}
thanks&regards
shadab akram khan

If you want to provide a feature of downloading PDF, get the content as byte[], and do the following:
response.setHeader("Content-Disposition", "attachment; filename=\"application.pdf\"");
response.setHeader("Pragma", "public");
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Cache-Control", "public");
response.setHeader("Content-Description", "File Transfer");
response.setContentType("application/pdf");
response.getOutputStream().write(pdfBytes);

Related

How to merge multiple PDF/A files and generate new PDF/A in java

I want to merge multiple PDF/A files and generated a new PDF/A file using java. I tried it with OpenPDF using PdfCopy class but it produced pdf document which does not conform to the PDF/A-1a standard.
Also tried with pdf-box and aspose-pdf library but did not work. Those are also producing normal PDF instead of PDF/A.
Getting following output with online pdf checker (https://www.pdf-online.com/osa/validate.aspx):
File: mergeusing_openPDF.pdf
Compliance: pdfa-1a
Result:
Document does not conform to PDF/A.
Details:
Validating file "mergeusing_openPDF.pdf" for conformance level pdfa-1a
The key MarkInfo is required but missing.
The key StructTreeRoot is required but missing.
The document does not conform to the requested standard.
The document doesn't provide appropriate logical structure information.
The document does not conform to the PDF/A-1a standard.
Done.
Posting a part of code of OpenPDF:
import java.awt.color.ICC_Profile;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import com.lowagie.text.Document;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;
public class ExampleMerge {
public static void main(String args[]) throws IOException {
List<String> pdfAFilesToMerge = Arrays.asList("D:/file1.pdf", "D:/file2.pdf");
String newFilePath = "D:/merge_using_openPDF.pdf";
PdfReader pdfReader = new PdfReader(pdfAFilesToMerge.get(0));
Document document = new Document(pdfReader.getPageSizeWithRotation(1));
PdfCopy copy = new PdfCopy(document, new FileOutputStream(newFilePath));
copy.setTagged();
copy.setPDFXConformance(PdfWriter.PDFA1A);
copy.createXmpMetadata();
document.open();
String iccProfilePath = "C:/ICC_Profiles/sRGB_IEC61966-2-1.icc";
ICC_Profile icc;
try {
icc = ICC_Profile.getInstance(new FileInputStream(iccProfilePath));
copy.setOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < pdfAFilesToMerge.size(); i++) {
for (int j = 1; j <= pdfReader.getNumberOfPages(); j++) {
PdfImportedPage page = copy.getImportedPage(pdfReader, j);
copy.addPage(page);
}
if (i + 1 < pdfAFilesToMerge.size())
pdfReader = new PdfReader(pdfAFilesToMerge.get(i + 1));
}
document.close();
System.out.println("Documents merged");
}
}

How do you convert an RTF file to a PDF file using iTextSharp

I have searched and I could not find an answer. For example, this doesn't work. My port:
static byte[] RtfToPdf(string rtf)
{
byte[] pdf = null;
using (var inputStream = GenerateStreamFromString(rtf))
using (var outputStream = new MemoryStream())
{
var pdfDocument = new iTextSharpDocument();
var pdfWriter = PdfWriter.GetInstance(pdfDocument, outputStream);
pdfDocument.Open();
RtfParser rtfParser = new RtfParser(null);
rtfParser.ConvertRtfDocument(inputStream, pdfDocument);
pdfDocument.Close();
pdfWriter.Close();
pdf = outputStream.ToArray();
}
return pdf;
}
public static MemoryStream GenerateStreamFromString(string value)
{
return new MemoryStream(Encoding.UTF8.GetBytes(value));
}
That simply copies the text of the RTF to a PDF without any of the formatting that was in the RTF. I am using iTextSharp-LGPL which is version 4.1.6 of iTextSharp.
I personally can't find any useful documentation. iText itself isn't intuitive so I'm having a hard time even guessing about what to try.

pdf generator Itext and JAX-RS

I would like to know how to create class that generates a pdf using Itext and send it over to a web browser using JAX-RS using the #GET and #Produces annotation.
Below is my solution, simplified to fit here. I'm using JDK 8 lambdas in the generate method, if you can't, just return an anonymous inner class implementing StreamOutput.
#Path("pdf")
#Produces(ContractResource.APPLICATION_PDF)
public class PdfResource {
public static final String APPLICATION_PDF = "application/pdf";
#GET
#Path("generate")
public StreamingOutput generate() {
return output -> {
try {
generate(output);
} catch (DocumentException e) {
throw new IOException("error generating PDF", e);
}
};
}
private void generate(OutputStream outputStream) throws IOException, DocumentException {
Document document = new Document();
PdfWriter.getInstance(document, outputStream);
document.open();
document.add(new Paragraph("Test"));
document.close();
}
}
Mock solution that serves PDF file on browser without storing a file on the server side with JAX-RS and IText 5 Legacy.
#Path("download/pdf")
public class MockPdfService{
#GET
#Path("/mockFile")
public Response downloadMockFile() {
try {
// mock document creation
com.itextpdf.text.Document document = new Document();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
com.itextpdf.text.pdf.PdfWriter.getInstance(document, byteArrayOutputStream);
document.open();
document.add(new Chunk("Sample text"));
document.close();
// mock response
return Response.ok(byteArrayOutputStream.toByteArray(), MediaType.APPLICATION_OCTET_STREAM)
.header("content-disposition", "attachment; filename = mockFile.pdf")
.build();
} catch (DocumentException ignored) {
return Response.serverError().build();
}
}
}

iText - Convert field names with square brackets to fields without square brackets?

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfStamper;
import java.util.Set;
import java.io.FileOutputStream;
public class PDFFile {
public static final String xfaForm3 = "C:/PDF_Service/pdf-project/src/sample.pdf";
public static final String dest = "sample2.xml";
public static void main(String[] args)
{
PdfReader reader;
PdfReader.unethicalreading = true;
AcroFields form;
try{
reader = new PdfReader(xfaForm3);
PdfStamper stamper2 = new PdfStamper(reader, new FileOutputStream(dest));
form = stamper2.getAcroFields();
stamper2.close();
Set<String> fldNames = form.getFields().keySet();
for (String fldName : fldNames)
{
System.out.println( fldName + " : " + form.getField( fldName ) );
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
My code above is reading a PDF file that has the XFA format and it prints out something that looks like this:
F[0].P1[0].FFField1[14] : 11 Pine Drive
Instead of printing out "F[0].P1[0].FFField1[14]", how can I print out "Address"?
I would like my code to print out this:
Address : 11 Pine Drive

Does jsoup support restful/rest request

Can you tell me please how to create http(s) request in jsoup with request method PUT or DELETE?
I came across this link:
https://github.com/jhy/jsoup/issues/158
but it is few years old, so hopefully there is some restful support implemented in that library.
As far as I can see HttpConnection object I can only use 'get' or 'post' request methods.
http://jsoup.org/apidocs/org/jsoup/helper/HttpConnection.html
http://jsoup.org/apidocs/org/jsoup/Connection.html
Jsoup doesn't support PUT nor DELETE methods. Since it is a parser, it doesn't need to support those operations. What you can do is use HttpURLConnection , which is the same that Jsoup uses underneath. With this you can use whatever method you want and in the end parse the result with jsoup (if you really need it).
Check this code :
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
String rawData = "RAW_DATA_HERE";
String url = "URL_HERE";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("METHOD_HERE"); //e.g POST
con.setRequestProperty("KEY_HERE", "VALUE_HERE"); //e.g key = Accept, value = application/json
con.setDoOutput(true);
OutputStreamWriter w = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
w.write(rawData);
w.close();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Response code : " + responseCode);
System.out.println(response.toString());
//Use Jsoup on response to parse it if it makes your work easier.
} catch(Exception e) {
e.printStackTrace();
}
}
}