Vaadin Convert and display image as PDF - java

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;
}

Related

Convert docx to pdf using Apache POI

The task is this, you need to create a printable form, replace the fields with the necessary data and convert to pdf format. Replacing text and saving in docx format is correct.
But when I run:
PdfConverter.getInstance().convert(document, outputStream, pdfOptions);
The fields that have been replaced are missing in the pdf file. The fields in the form are entered in the form for tex (figure), you can see it in the photo.
If you insert into plain text, then the replacement is correct. I think that you need to somehow configure PdfOptions, but so far there are no options for how to do it ...
If someone had such a problem and has suggestions on what to try to do, I will be glad for help))
The code that converts the finished form:
`InputStream inputStream = ByteSource.wrap(printFileDTO.getContent()).openStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PdfOptions pdfOptions = PdfOptions.create();
pdfOptions.fontProvider((familyName, encoding, size, style, color) -> {
try {
BaseFont baseFont =
BaseFont.createFont(TNR, encoding, BaseFont.EMBEDDED);
return new Font(baseFont, size, style, color);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
XWPFDocument document = new XWPFDocument(inputStream);
PdfConverter.getInstance().convert(document, outputStream, pdfOptions);`
Versions:
<apache.poi>5.2.3</apache.poi> <poi.ooxml.version>5.2.3</poi.ooxml.version> <poi.scratchpad.version>5.2.3</poi.scratchpad.version> <opensagres.xdocreport.version>2.0.3</opensagres.xdocreport.version>
Updated to the latest to try, but it did not change anything
Piece of completed form:
enter image description here

How to set PDF open page number from PDFMergerUtility

I am merging PDF content using PDFMergerUtility in Java.
PDFMergerUtility bundle= new PDFMergerUtility();
bundle.addSource(new ByteArrayInputStream(contentService.retrieveData(transaction1);
bundle.addSource(new ByteArrayInputStream(contentService.retrieveData(transaction2);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream()
bundle.setDestinationStream(outputStream); // setting outputstream
bundle.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
return outputStream.toByteArray(); // returning result
But by default it is opening on the last page of PDF when I try to open the resultant PDF. I am not using PDocument for these as
these are entity based documents. Due to this unable to use this below method. Can you please suggest any approach to directly set the opened page number in PDFMergerUtility.
PDPageXYZDestination destination = new PDPageXYZDestination();
destination .setPageNumber(num);
PDActionGoTo action = new PDActionGoTo();
action.setDestination(destination );
pdf.getDocumentCatalog().setOpenAction(action);

droidtext adding image doesn't work

I am desperately trying to insert an image into an existing pdf with droidtext.
The original version of this project was made with iText.
So the code already exists and was modified to fit for Android.
What I do is I take an existing PDF as background.
Insert text and crosses at specified positions within this pdf.
Like filling out a form.
This works quite well so far without changing the code drastically.
Now I want to set an image to the bottom of the page to sign the form.
I used my original code and adapted it a little.
Which doesn't work at all.
I tried to set the image at a specific position. Maybe that was the error.
So i tried to do it the "official" way.
The Pengiuns.jpg image is located on the sd-card.
try {
Document document = new Document();
File f=new File(Environment.getExternalStorageDirectory(), "SimpleImages.pdf");
PdfWriter.getInstance(document,new FileOutputStream(f));
document.open();
document.add(new Paragraph("Simple Image"));
String path = Environment.getExternalStorageDirectory()+"/Penguins.jpg";
if (new File(path).exists()) {
System.out.println("filesize: " + path + " = " + new File(path).length());
}
Image image =Image.getInstance(path);
document.add(image);
document.close();
} catch (Exception ex) {
System.out.println("narf");
}
But still no image at all.
What I get is an PDF with the words "Simple Image" on it and nothing else.
I can access the picture. I get the correct filesize by the if().
No exceptions are thrown.
So my questions are, how do I get an Image located on the SD-Card into my pdf?
What is the mistake here?
But most importantly how do I set the image to a specific location with size within the pdf?
In my original code i use setAbsolutePosition( x, y ) for that.
Eclipse is not complaining when I use it in the code but is it really working?
The reason why you are getting the "Simple Image" is because you have it in Paragraph. In order to add an image, use:
Image myImg1 = Image.getInstance(stream1.toByteArray());
If you want to have it as a footer in the last page you can use the following code but it works with text. You can try to manipulate it for image:
Phrase footerText = new Phrase("THIS REPORT HAS BEEN GENERATED USING INSPECTIONREPORT APP");
HeaderFooter pdfFooter = new HeaderFooter(footerText, false);
doc.setFooter(pdfFooter);
Here is sample code. Here I have uploaded an image to Imageview and then added to pdf. Hope this helps.
private String NameOfFolder = "/InspectionReport";
Document doc = new Document();
try { //Path to look for App folder
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + NameOfFolder;
String CurrentDateAndTime= getCurrentDateAndTime();
// If App folder is not there then create one
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();
//Creating new file and naming it
int i = 1;
File file = new File(dir, "Inspection"+Integer.toString(i)+"-" + CurrentDateAndTime+".pdf");
while(file.exists()) {
file = new File(dir, "Inspection"+Integer.toString(i++)+"-" + CurrentDateAndTime+".pdf");}
String filep= file.toString();
FileOutputStream fOut = new FileOutputStream(file);
Log.d("PDFCreator", "PDF Path: " + path);
PdfWriter.getInstance(doc, fOut);
Toast.makeText(getApplicationContext(),filep , Toast.LENGTH_LONG).show();
//open the document
doc.open();
ImageView img1 = (ImageView)findViewById(R.id.img1);
ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
Bitmap bitmap1 = ((BitmapDrawable)img1.getDrawable()).getBitmap();
bitmap1.compress(Bitmap.CompressFormat.JPEG, 100 , stream1);
Image myImg1 = Image.getInstance(stream1.toByteArray());
myImg1.setAlignment(Image.MIDDLE);
doc.add(myImg1);
Try following code:
/* Inserting Image in PDF */
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getBaseContext().getResources(), R.drawable.android);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.setAlignment(Image.MIDDLE);
//add image to document
doc.add(myImg);

java generate PDF in separate class but return from controller

I'm trying to add a PDF generator to my website. Everything works fine as far as the generator in the controller
ConsumerController.java:
public String downloadPDF(#PathVariable("id") Long id, #PathVariable("transaction") Long transaction, Model uiModel, HttpServletRequest httpServletRequest, HttpServletResponse response) {
Document document = new Document();
try{
response.setContentType("application/pdf");
PdfWriter.getInstance(document, response.getOutputStream());
document.open();
document.add(new Paragraph("Hello Kiran"));
document.add(new Paragraph("Hello" + id));
document.add(new Paragraph("For"+ transaction));
document.add(new Paragraph(new Date().toString()));
}catch(Exception e){
e.printStackTrace();
}
document.close();
return null;
}
this is what i have at the moment and this is exactly how i want it to work, but the one i would like to add would be better off in its own class (code below).
PDFGenerator.java:
public void generatorPDF() throws Exception{
Document d = new Document();
try{
PdfWriter writer = PdfWriter.getInstance(d, new FileOutputStream("CodeOfDoom.pdf"));
d.open();
for(int i=0; i<10; i++){
PdfPTable table = generateLineItemTable(_order.getLineItems());
PdfPTable headerTable= generateHeaderTable(_order.getCustomer());
addBarcode(writer,headerTable);
//add customer barcode to the header
d.add(headerTable);
d.add(table);
Paragraph p = new Paragraph("\n\nFor more, please visit ");
Anchor anchor = new Anchor("www.codeofdoom.com/wordpress");
p.add(anchor);
d.add(p);
d.newPage();
}
d.close();
}catch(Exception e){
e.printStackTrace();
}
}
so far with anything that i have tried, the PDF writer seems to be the issue, because I'm not sure how to go about adding the document to the writer from a separate class
In the first instance, you're creating the PDF and writing it directly to the response stream. In the second class, you are writing it to a file.
If you want to create the PDF in a different class, one solution would be to pass the output stream into the constructor of the class. If you don't want to pass a reference to the output stream, you could create the PDF in memory by writing to a ByteArrayOutputStream and then return the generated array of bytes. With that approach, you could then write the generated PDF bytes back to the response stream. This approach assumes your PDF is small enough to fit into memory, though.

Get empty image when transcoding SVG to PNG

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.

Categories

Resources