I recently used pdfbox android library because iText is under AGPL. I tried running following code.
PDDocument document = new PDDocument();
PDPage page= new PDPage();
document.addPage(page);
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
Bitmap bitmap=BitmapFactory.decodeFile(imagesObject.get(0).image); //imagesobject is string path
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
PDImageXObject pdImage = PDImageXObject.createFromFile(imagesObject.get(0).image,document);
PDPageContentStream contentStream = new PDPageContentStream(document, page,true,true);
contentStream.drawImage(pdImage,70,70,pdImage.getWidth(), pdImage.getHeight());
contentStream.close();
document.save(file);
document.close();
PDF is saved with empty page no image is shown. I noticed size of pdf is 6mb, Which means the image has been drawn but can't see. Any Fix?
Also I am using ported library by TomRoush.
This is the link for pdf that was generated here
As discussed in the comments, the image had a .jpg extension in the name, but was a PNG image file. The PDImageXObject createFromFile(String imagePath, PDDocument doc) method assumes the file type by its extension, so it embedded the file 1:1 in the PDF and assigned a DCT filter. Both of these would have been correct for a jpeg file, but not for png.
So the solution would be to either rename the file, or use the createFromFileByContent method.
Related
i try to write a java program, which converts the pptx to jpeg images. There are many options (e.g., aspose, groupdocs, cloudmersive). But they are limited (either generating images in the evaluation mode or limited by the number of API calls); i prefer an open source library and up till now, i have known 2 libreries which are Apache POI and Docx4j. By using the Apache POI, i was able to implement the conversion PPTX-JPEG; however, the generated images' quality is low even the rendering parameters were set.
// create an empty presentation
public static void Pptx_Img(String slidePath, String outputDir, String fileName) throws Exception {
// create an empty presentation
File file = new File(slidePath);
FileInputStream in = new FileInputStream(file);
XMLSlideShow ppt = new XMLSlideShow(in);
// get the dimension and size of the slide
Dimension pgsize = ppt.getPageSize();
List<XSLFSlide> slides = ppt.getSlides();
JPEGImageWriteParam jpegParams = new JPEGImageWriteParam(null);
jpegParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
jpegParams.setCompressionQuality(1f);
BufferedImage img = null;
outputDir = outputDir + "\\apache\\pptx\\" + fileName;
Apache.createDirIfNotExists(outputDir);
for (int i = 0; i < 10; i++) {
img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
graphics.setRenderingHint(Drawable.BUFFERED_IMAGE, new WeakReference<>(img));
// clear area
graphics.setPaint(Color.white);
graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
// draw the images
slides.get(i).draw(graphics);
FileOutputStream out = new FileOutputStream(outputDir + "\\slide_" + i + ".jpg");
/*
// specifies where the jpg image has to be written
final ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
writer.setOutput(ImageIO.createImageOutputStream(out));
// writes the file with given compression level
writer.write(null, new IIOImage(img, null, null), jpegParams);
*/
ImageIO.write(img, "jpeg", out);
ppt.write(out);
graphics.dispose();
out.close();
img.flush();
}
System.out.println("Images successfully created");
in.close();
ppt.close();
}
Comparison between the original slide and the generated images
I also came up with another indirect way, which converts pptx-pdf-jpeg (because i have the implementation for conversion pdf-jpeg and the conversion can actually maintain the image quality). But i couldnt find any open source libs which can do the conversion pptx-jpeg. For Apache POI, it can convert pptx-pdf but the mechanism is just similar to pptx-jpeg: writes the Graphic2D-instance to pdf instead of jpeg, which basically does not improve the rendering quality.
Added: Regarding to the comparison, the wrong rendering is also another issue !
I have a file (for example JPEG size 1588 × 2244px). It's generated by puppeteer (but phantomjs also generate 72 DPI screenshot). When I save this image into a file with .jpeg extension and I use macOS General Info I see:
As you can see it has 72 DPI set in metadata, but I want to use file with 300 DPI. I know, that in digital it doesn't change anything - it's property for printing, but I don't want to explain to each customer that this file could be print in 300 DPI.
When I use Gimp and Image > Print Size
I can change the DPI, and export a picture again. And now it has 300 DPI in General Info window.
I try to do it in Node.JS server, but I found few options to change this property on .PNG pictures, but anyone is working for .JPEG files.
I think that the most accurate option is to use method changeDpiDataUrl from this library:
https://github.com/shutterstock/changeDPI/blob/master/src/index.js
But when I put my image as base64image, after a split operation I have the array with 1 element only - I think that this is body, so I don't have format property (at 63 line).
Anybody meet this problem before?
You can use the library piexifjs to change the EXIF data of an image. The library only changes the meta data (called EXIF), not the image itself.
Code Sample
The following code uses the API to read the EXIF data of an image, change it and create a new buffer from the changed data.
const piexif = require("piexifjs");
// get the image buffer from puppeteer or from disk
const imageBuffer = /* ... */
// convert buffer to string and load it
const imageString = imageBuffer.toString('binary');
const exif = piexif.load(imageString);
// change resolution
exif['0th'][piexif.ImageIFD.XResolution] = [300,1];
exif['0th'][piexif.ImageIFD.YResolution] = [300,1];
// generate new EXIF data
const newExifDump = piexif.dump(exif);
// generate new image
const newData = piexif.insert(newExifDump, imageString);
const jpgBuffer = new Buffer(newData, "binary");
// write to file or use buffer
// ...
Be aware, that I have not used the library myself, nor have I tested the code.
This solution is another alternative to the answer given by #thomasdondorf.
The resolution/density can be set easily using JavaScript standard image processing library sharp by withMetadata function.
Simple example:
// Set output metadata to 96 DPI
const data = await sharp(input)
.withMetadata({ density: 96 })
.toBuffer();
Npm module: sharp
I want to create a chart with Object Refinery JFreeChart. After that, I want to create a pdf with Apache PDFBox, where I use the chart from JFreeChart. When I save the chart as png or jpg, then the quality of the chart is very bad. So I save the chart as svg and convert it with Apache Batik to pdf. The quality in the pdf is good but I can't alter the position of the chart in the pdf.
How can I alter the position of the chart?
Is there a better solution to generate a chart as svg and put it in a pdf?
Here is my code of how I convert the svg to pdf:
public void convertSVGtoPDF() throws TranscoderException, IOException{
//Step -1: We read the input SVG document into Transcoder Input
String svg_URI_input =
Paths.get("output_pie_chart.svg").toUri().toURL().toString();
System.out.println("Path="+svg_URI_input);
TranscoderInput input_svg_image = new TranscoderInput(svg_URI_input);
//Step-2: Define OutputStream to PDF file and attach to TranscoderOutput
OutputStream pdf_ostream = new FileOutputStream("FinalPDF.pdf");
TranscoderOutput output_pdf_file = new TranscoderOutput(pdf_ostream);
// Step-3: Create a PDF Transcoder and define hints
Transcoder transcoder = new PDFTranscoder();
transcoder.addTranscodingHint(SVGAbstractTranscoder.KEY_HEIGHT, new
Float(800)); transcoder.addTranscodingHint(SVGAbstractTranscoder.KEY_WIDTH, new Float(800));
transcoder.addTranscodingHint(PrintTranscoder.KEY_MARGIN_TOP,new Float (80));
// Step-4: Write output to PDF format
transcoder.transcode(input_svg_image, output_pdf_file);
// Step 5- close / flush Output Stream
pdf_ostream.flush();
pdf_ostream.close();
}
}
I am trying to paste a 'JPEG' image file to Excel 2013 32-bit version. But after writing the workbook when I am opening it I am getting an error "The image cannot currently be displayed". The image file is very large.
I am using Windows 7 64 bit with Microsoft Excel 32 bit verison.
here is the portion of code to paste the image following the apache POI documentation. -
XSSFDrawing drawing = sheet.createDrawingPatriarch();
InputStream graphImage = new FileInputStream(fileName);
//Byte array to store the Image in Byte format
byte[] bytes = IOUtils.toByteArray(graphImage);
//Image Id
int imageId = frameWorkbook.addPicture(bytes,Workbook.PICTURE_TYPE_JPEG);
graphImage.close();
//Instance of ClientAnchor
ClientAnchor anchor = new XSSFClientAnchor();
anchor.setAnchorType(ClientAnchor.DONT_MOVE_AND_RESIZE);
//Setting start position of the Image
anchor.setCol1(5);
anchor.setRow1(5);
//Instance of XSSFpicture to paint the image
XSSFPicture picOfGraph = drawing.createPicture(anchor,imageId);
picOfGraph.resize();
This code works fine with small size image but if the image size gets larger then I am getting the error????Any solution??
In my application I have one html template which brings dynamic data from DB. I need to convert that html file(template) to PDF. Is there any package to convert the raw html to PDF in node.js? I go through with pdfcrowd and livedocx. Both using some webservices for conversion which does not suits for my specification. please suggest some package for converting HTML to PDF in local machine..?
Go through this link..
Here u can convert HTML file to PDF or HTML content to PDF
import NDHTMLtoPDF.h and NDHTMLtoPDF.m from above source link
pass HTML file path to generate PDF here..
NSURL *targetURL = [NSURL fileURLWithPath:HTMLPath];
Converting HTML to PDF
self.PDFCreator = [NDHTMLtoPDF createPDFWithURL:targetURL
pathForPDF:[[NSString stringWithFormat:#"~/Documents/Sample.pdf"] stringByExpandingTildeInPath]
delegate:self
pageSize:kPaperSizeA4
margins:UIEdgeInsetsMake(20, 5, 90, 5)];
pass HTML Content to generate PDF here..
NSString *str_PDFName_path = [NSString stringWithFormat:#"~/Documents/Sample.pdf"];
self.PDFCreator = [NDHTMLtoPDF createPDFWithHTML:str_HTML pathForPDF:[str_PDFName_path stringByExpandingTildeInPath] delegate:self pageSize:kPaperSizeA4 margins:UIEdgeInsetsMake(20, 5, 90, 5)];