I generate a docx document in runtime and I want to convert it to PDF without actually saving the file locally
public byte[] convertToPDF(byte[] docxDocument) {
try {
InputStream doc = new ByteArrayInputStream(docxDocument);
XWPFDocument xwpfDocument = new XWPFDocument(doc);
PdfOptions options = PdfOptions.create();
OutputStream out = new ByteArrayOutputStream();
PdfConverter.getInstance().convert(xwpfDocument, out, options);
//return data; ???
} catch (IOException e) {
LOGGER.error("Could not convert docx to PDF", e);
}
}
PdfConverter is void. How can I achieve this?
I think you should use out which keeps the converted data
return out.toByteArray();
Related
I am creating a pdf file and storing it in a directory. I now want to pass back the pdf data so the user can download it to their preferred directory (i.e., no longer create the file in the directory). How do I create the "pdfData" to pass back please?
I understand that it would involve replaceing "new FileOutputStream(FILE)" with the name of the variable to store the data in; however, I can not work it out or find an example online.
I have:
String filePath = System.getProperty("user.home") + "\\Documents\\"+fileName; //Test use
Document document = new Document(PageSize.A4, 72f, 72f, 72f, 72f);
try {
PdfWriter.getInstance(document, new FileOutputStream(FILE));
document.open();
addMetaData(document);
addImages(document);
addTitlePage(document, recipeDetails, recipeName, servings, servingSize);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
//return pdfData;
To show what mkl suggested merged in with your code:
String filePath = System.getProperty("user.home") + "\\Documents\\"+fileName; //Test use
Document document = new Document(PageSize.A4, 72f, 72f, 72f, 72f);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);
document.open();
addMetaData(document);
addImages(document);
addTitlePage(document, recipeDetails, recipeName, servings, servingSize);
document.close();
byte[] pdfData = baos.toByteArray();
return pdfData;
} catch (Exception e) {
e.printStackTrace();
}
The pdfData is a byte[] (byte array). This can be directly streamed/stored anywhere as the actual pdf. Just keep in mind that this is writing the PDF into memory, so you have scalability issue if doing lots of large PDFs concurrently.
I hope that helps.
Does anyone know how image file can be easily converted into PDF format. What I need is to get the image from database and display it on the screen as PDF. What am I doing wrong? I tried to use iText but with no results.
My code:
StreamResource resource = file.downloadFromDatabase();//get file from db
Document converToPdf=new Document();//Create Document Object
PdfWriter.getInstance(convertToPdf, new FileOutputStream(""));//Create PdfWriter for Document to hold physical file
convertToPdf.open();
Image convertJpg=Image.getInstance(resource); //Get the input image to Convert to PDF
convertToPdf.add(convertJpg);//Add image to Document
Embedded pdf = new Embedded("", convertToPdf);//display document
pdf.setMimeType("application/pdf");
pdf.setType(Embedded.TYPE_BROWSER);
pdf.setSizeFull();
Thanks.
You're not using iText correctly:
You never close your writer, so the addition of the image never gets written to the outputstream.
You pass an empty string to your FileOutputStream. If you want to keep the pdf in memory, use a ByteArrayOutputStream. If not, define a temporary name instead.
You pass your Document object, which is a iText-specific object to your Embedded object and treat it like a file. It is not a pdf-file or byte[]. You'll probably want to pass either your ByteArrayOutputStream or read the temp file as a ByteArrayOutputStream into memory and pass that to Embedded.
Maybe someone will use (Vaadin + iText)
Button but = new Button("FV");
StreamResource myResource = getPDFStream();
FileDownloader fileDownloader = new FileDownloader(myResource);
fileDownloader.extend(but);
hboxBottom.addComponent( but );
private StreamResource getPDFStream() {
StreamResource.StreamSource source = new StreamResource.StreamSource() {
public InputStream getStream() {
// step 1
com.itextpdf.text.Document document = new com.itextpdf.text.Document();
// step 2
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
com.itextpdf.text.pdf.PdfWriter.getInstance(document, baos);
// step 3
document.open();
document.add(Chunk.NEWLINE); //Something like in HTML :-)
document.add(new Paragraph("TEST" ));
document.add(Chunk.NEWLINE); //Something like in HTML :-)
document.newPage(); //Opened new page
//document.add(list); //In the new page we are going to add list
document.close();
//file.close();
System.out.println("Pdf created successfully..");
} catch (DocumentException ex) {
Logger.getLogger(WndOrderZwd.class.getName()).log(Level.SEVERE, null, ex);
}
ByteArrayOutputStream stream = baos;
InputStream input = new ByteArrayInputStream(stream.toByteArray());
return input;
}
};
StreamResource resource = new StreamResource ( source, "test.pdf" );
return resource;
}
I can successfully generate a pdf from an html string, but the problem is that it doesn't take the css script. How can I generate the pdf with css style?
Please help! I have tried cssresolver als
My code is here:
{String result = "failed";
try
{
String html2 ="<html>"+.....+"</html>" ;
long timemilli = System.currentTimeMillis();
String filename = "EastAfriPack2014_Ticket_"+timemilli;
String writePath = Global.PDF_SAVE_PATH + filename ;
System.out.println("----------writePath--------------"+ writePath);
OutputStream file = new FileOutputStream(new File(writePath+".pdf"));
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, file);
document.open();
InputStream is = new ByteArrayInputStream(k.getBytes());
CSSResolver cssResolver = XMLWorkerHelper.getInstance().getDefaultCssResolver(false);
cssResolver.addCss("table {color: red; background-color: blue; } ", true);
XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
document.close();
file.close();
System.out.println("pdf created");
result = filename;
return filename;
} catch (Exception e) {
e.printStackTrace();
return result;
}
}
I don't think your approach works. I tried it before because, its the easiest way to create a PDF from HTML, but got bitten by same problem.
You either provide the styles inline via style attribute for the table
or
use the HTML, CSS files separately and send them to the HelperClass
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
new FileInputStream("myhtmlFile.html"),
new FileInputStream("myCSSFile.css"));
the HTML part can also be an inputStream you made above in the code.
I'm trying to update a Microsoft Word document using Apache POI. The msword document is a template that contains a number of placeholders in the form "${place.holder}" and all I need to do is to replace the holders with specific values. What I've got so far is
private void start() throws FileNotFoundException, IOException {
POIFSFileSystem fsfilesystem = null;
HWPFDocument hwpfdoc = null;
InputStream resourceAsStream = getClass().getResourceAsStream("/path/to/document/templates/RMA FORM.doc");
try {
fsfilesystem = new POIFSFileSystem(resourceAsStream );
hwpfdoc = new HWPFDocument(fsfilesystem);
Range range = hwpfdoc.getRange();
range.replaceText("${rma.number}","08739");
range.replaceText("${customer.name}", "Roger Swann");
FileOutputStream fos = new FileOutputStream(new File("C:\\temp\\updatedTemplate.doc"));
hwpfdoc.write(fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The program runs without errors. If I look in the output file with a Hex editor I can see that the placeholders have been replaced by the program. However, when I try to open the document with MSWord, MSWord crashes.
Is there a step (series of steps) that I'm missing, or am I basically out of luck with this? Do I need to adjust any counters because the length of the replacement text is not the same as the length of the replaced text?
Regards
use new FileInputStream() instead of getClass().getResourceAsStream("/path/to/document/templates/RMA FORM.doc");
I'm trying to generate an SVG image and then transcode it to PNG using Apache Batik. However, I end up with an empty image and I can't see why.
I use the Document from SVGDomImplementation as the base for my transcoding (to avoid writing the SVG to disk and loading it again). Here's an example:
DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation();
String namespace = SVGDOMImplementation.SVG_NAMESPACE_URI;
Document document = domImpl.createDocument(namespace, "svg", null);
//stuff that builds SVG (and works)
TranscoderInput transcoderInput = new TranscoderInput(svgGenerator.getDOMFactory());
PNGTranscoder transcoder = new PNGTranscoder();
transcoder.addTranscodingHint(PNGTranscoder.KEY_WIDTH, new Float(svgWidth));
transcoder.addTranscodingHint(PNGTranscoder.KEY_HEIGHT, new Float(svgHeight));
try {
File temp = File.createTempFile(key, ".png");
FileOutputStream outputstream = new FileOutputStream(temp);
TranscoderOutput output = new TranscoderOutput(outputstream);
transcoder.transcode(transcoderInput, output);
outputstream.flush();
outputstream.close();
name = temp.getName();
} catch (IOException ioex) {
ioex.printStackTrace();
} catch (TranscoderException trex) {
trex.printStackTrace();
}
My problem is that the resulting image is empty and I can't see why. Any hints?
I think it depends on how you're creating the SVG document. What are you using svgGenerator for (which I assume is an SVGGraphics2D)?
TranscoderInput transcoderInput = new TranscoderInput(svgGenerator.getDOMFactory());
If you've built up the SVG document in document, then you should pass it to the TranscoderInput constructor.
This page has an example of rasterizing an SVG DOM to a JPEG.