Convert svg chart to pdf and alter chart position - svg

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

Related

Convert pptx to images using java

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 !

Pdfbox-Android shows empty page

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.

How to convert pptx slides to a single svg image with aspose slides?

I was able to convert each pptx slide to multiples/separate svg images with the following code:
//Getting last slide index
int lastSlidePosition=presentation.getSlides().size();
SlideEx slide =null;
//Iterating through every presentation slide and generating SVG image
for (int i = 0; i < lastSlidePosition; i++)
{
//Accessing Slides
slide = presentation.getSlides().get_Item(i);
slide.writeAsSvg(new FileOutputStream(path + i + ".svg"));
}
But I whant to converte all pptx slides to a single svg file.
The whole presentation cannot be saved to a single svg using Aspose.Slides. However, you can do
Pptx to pdf
And then PDF to svg using Aspose.Pdf.

Apache POI insert image without anchor

I'm creating Excel file in Java using Apache POI, it works but the inserted image is anchored to columns / rows. There are 2 issues with this method:
The image doesn't keep the original size (get stretched a little bit).
When resizing the columns/rows the image get stretched. Is there any way to insert an image to Excel without anchor? (same as using Excel / Insert / Picture)
I'm using the following example from Apache POI document page:
//create a new workbook
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
//add picture data to this workbook.
InputStream is = new FileInputStream("image1.jpeg");
byte[] bytes = IOUtils.toByteArray(is);
int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
is.close();
CreationHelper helper = wb.getCreationHelper();
//create sheet
Sheet sheet = wb.createSheet();
// Create the drawing patriarch. This is the top level container for all shapes.
Drawing drawing = sheet.createDrawingPatriarch();
//add a picture shape
ClientAnchor anchor = helper.createClientAnchor();
//set top-left corner of the picture,
//subsequent call of Picture#resize() will operate relative to it
anchor.setCol1(3);
anchor.setRow1(2);
Picture pict = drawing.createPicture(anchor, pictureIdx);
//auto-size picture relative to its top-left corner
pict.resize();
//save workbook
String file = "picture.xls";
if(wb instanceof XSSFWorkbook) file += "x";
FileOutputStream fileOut = new FileOutputStream(file);
wb.write(fileOut);
fileOut.close();
Thanks for your answer.
Proably that because of this comment in method 'resize' javadoc:
Please note, that this method works correctly only for workbooks with the default font size (Arial 10pt for .xls and Calibri 11pt for .xlsx). If the default font is changed the resized image can be streched vertically or horizontally.

Large image not displaying in Excel using Apache POI

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??

Resources