i have a problem with Apahe POI using XSLF to convert presentation slides to images. The issue is that sometimes there are missing elements on pictures, most of the time background template images or some template shapes.
For conversion im using following code:
package com.itpharma.videocall.poi;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
public class PPTX2PNG {
public static void main(String[] args) {
String prezName = "presentation";
try {
File fin = new File(prezName + ".pptx");
FileInputStream fis = new FileInputStream(fin);
XMLSlideShow ppt = new XMLSlideShow(fis);
Dimension pptSize = ppt.getPageSize();
System.out.println("Presentation size: " + pptSize.width + " x " + pptSize.height);
ppt.getSlides().forEach(slide -> {
System.out.println(slide.getSlideNumber() + ": " + slide.getTitle());
BufferedImage img = new BufferedImage(pptSize.width, pptSize.height, 1);
Graphics2D gfx = img.createGraphics();
gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
gfx.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
gfx.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
gfx.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
gfx.setColor(Color.WHITE);
gfx.clearRect(0, 0, pptSize.width, pptSize.height);
gfx.fill(new Rectangle2D.Float(0, 0, pptSize.width, pptSize.height));
slide.draw(gfx);
try {
File fout = new File(prezName + "-slide-" + slide.getSlideNumber() + ".png");
FileOutputStream fos = new FileOutputStream(fout);
javax.imageio.ImageIO.write(img, "png", fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
});
ppt.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Im using POI 3.15 version (latest stable), Eclipse Oxygen on MacOS 10.12.2 for development (production would be on ubuntu VPS) and i dont know what is going wrong, if its my code or my system or POI library or my imports or i dont know.
I attached few images where i used the same presentation and only changed design templates. In upper part of image is PowerPoin screenshot and in lower part are generated images with missing parts. Third template did produce an error an no images.
First template:
Second template:
Third template:
With last template i get following error:
Exception in thread "main" java.lang.IllegalArgumentException: Relationship null doesn't start with this part /ppt/slides/slide1.xml
at org.apache.poi.openxml4j.opc.PackagePart.getRelatedPart(PackagePart.java:469)
at org.apache.poi.xslf.usermodel.XSLFShape$2.getPart(XSLFShape.java:392)
at org.apache.poi.xslf.usermodel.XSLFShape$2.getImageData(XSLFShape.java:400)
at org.apache.poi.sl.draw.DrawPaint.getTexturePaint(DrawPaint.java:135)
at org.apache.poi.sl.draw.DrawPaint.getPaint(DrawPaint.java:112)
at org.apache.poi.sl.draw.DrawTextParagraph.getAttributedString(DrawTextParagraph.java:530)
at org.apache.poi.sl.draw.DrawTextParagraph.breakText(DrawTextParagraph.java:235)
at org.apache.poi.sl.draw.DrawTextShape.drawParagraphs(DrawTextShape.java:158)
at org.apache.poi.sl.draw.DrawTextShape.getTextHeight(DrawTextShape.java:219)
at org.apache.poi.sl.draw.DrawTextShape.drawContent(DrawTextShape.java:102)
at org.apache.poi.sl.draw.DrawSimpleShape.draw(DrawSimpleShape.java:93)
at org.apache.poi.sl.draw.DrawSheet.draw(DrawSheet.java:67)
at org.apache.poi.sl.draw.DrawSlide.draw(DrawSlide.java:39)
at org.apache.poi.xslf.usermodel.XSLFSlide.draw(XSLFSlide.java:301)
at com.itpharma.videocall.poi.PPTX2PNG.lambda$0(PPTX2PNG.java:48)
at java.util.ArrayList.forEach(ArrayList.java:1249)
at com.itpharma.videocall.poi.PPTX2PNG.main(PPTX2PNG.java:32)
I have also tested with other templates and with some custom made presentations and there are almost every time missing some shapes or background.
Related
I am using zxing api for creating barcode. But while creating i am not able to write barcode content as label below the barcode.
output --
output required --
The code to generate these barcode are as such -
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
public class BarcodeTesting {
private static void wrtieToStream(BitMatrix bitMatrix) {
try {
MatrixToImageWriter.writeToStream(bitMatrix, "png", new FileOutputStream(new File("hello" + ".png")));
System.out.println( " Barcode Generated.");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private BitMatrix generateBitMatrix(String content, BarcodeFormat format, int width, int height) {
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix bitMatrix = null;
try {
bitMatrix = writer.encode(content, format, width, height);
} catch (WriterException e) {
e.printStackTrace();
}
return bitMatrix;
}
public static void main(String[] args) {
BarcodeTesting obj = new BarcodeTesting();
BarcodeFormat barcodeFormat = BarcodeFormat.QR_CODE;
BitMatrix bitMatrix = obj.generateBitMatrix("MY QR Code 123", barcodeFormat, 24, 24);
// String formatString = format.toString();
wrtieToStream(bitMatrix);
}
}
As the QRCode specifiaction does not provide an option to include the content into the image I do not think zxing or any other barcode generator does offer this functionality. You will have to add the text to the image on your own. Be aware that you have to leave enough white space around the QRCode. Your above image doesn't have enough whitespace at the bottom.
#tobltobs. I search a lot but didn't find any way in zxing api to do as i am expecting . So as per your suggestion i created a image in which i pasted my barcode after generating & reading it.Then i write barcode content as String below that image .
Barcode4j can be used to embed text along with the bar code.
This link has working java code.
My code is
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import org.dcm4che2.imageio.plugins.dcm.DicomImageReadParam;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class DicomToJpeg {
public static void main(String args[]) throws IOException, Exception
{
dicomToJpeg("d:/F74AFBC7");
}
public static void dicomToJpeg(String args) throws IOException, Exception {
// TODO Auto-generated method stub
try
{
File myDicomFile = new File(args);
BufferedImage myJpegImage = null;
Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM");
ImageReader reader = (ImageReader) iter.next();
DicomImageReadParam param = null;
try{
param = (DicomImageReadParam) reader.getDefaultReadParam();
}
catch (Exception e) {
e.printStackTrace();
}
ImageInputStream iis=ImageIO.createImageInputStream(myDicomFile);
reader.setInput(iis, false);
myJpegImage = reader.read(0, param);
iis.close();
if (myJpegImage == null) {
System.out.println("\nError: couldn't read dicom image!");
return;
}
File myJpegFile = new File("d:/demo.jpg");
OutputStream output = new BufferedOutputStream(new FileOutputStream(myJpegFile));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output);
encoder.encode(myJpegImage);
System.out.println("Image Create successufully");
output.close();
}
catch(IOException e){
System.out.println("\nError: couldn't read dicom image!"+ e.getMessage());
return;
}
}
}
When i execute in java project using eclipse it work fine...
But when i execute using web application and in this i call it from controller page like
DicomToJpeg.dicomToJpeg("d:/F74AFBC7");
then it gives error like...
java.util.NoSuchElementException
at javax.imageio.spi.FilterIterator.next(Unknown Source)
at javax.imageio.ImageIO$ImageReaderIterator.next(Unknown Source)
at javax.imageio.ImageIO$ImageReaderIterator.next(Unknown Source)
at com.lifecare.controller.DicomToJpeg.dicomToJpeg(DicomToJpeg.java:32)
How to solve this error please help me....
The javadoc to ImageIO.getImageREadersByFormatName says:
Returns an Iterator containing all currently registered ImageReaders
that claim to be able to decode the named format.
If you access the iterator without checking if it has an element, you will get an exception.
Since it runs in you IDE and not on the server, you may have a look if the image readers for the DICOM is in the application's classpath on the server.
However, I would also like to know how do you call the above class. Is it from a servlet?
I solved it by calling ImageIO.scanForPlugins() before ImageIO.getImageReadersByFormatName()
ImageIO.scanForPlugins()
Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM");
ImageReader reader = (ImageReader) iter.next();
This works perfectly on servlets
Try like this
BufferImage bi = ImageIO.read(dcm file name with path);
ImageIO.write(enter pathname with filename, format);
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.codec.Base64.OutputStream;
import java.io.FileOutputStream;
import java.io.StringReader;
import java.net.URL;
public class myclass {
public static void main(String[] args) {
String result = "<html><body><div>(i) the recognised association shall have the approval of the Forward Markets Commission established under the Forward Contracts (Regulation) Act, 1952 (74 of 1952) in respect of trading in derivatives and shall function in accordance with the guidelines or conditions laid down by the Forward Markets Commission; </div> <body> </html>";
Document document = new Document();
OutputStream file = null;
try {
PdfWriter.getInstance(document, new FileOutputStream(
"E://Image.pdf"));
document.open();
PdfWriter.getInstance(document, file);
document.open();
#SuppressWarnings("deprecation")
HTMLWorker htmlWorker = new HTMLWorker(document);
htmlWorker.parse(new StringReader(result));
String imageUrl = "http://www.taxmann.com/emailer/demo/mobileAapp/newAppDesign.jpg";
Image image2 = Image.getInstance(new URL(imageUrl));
document.add(image2);
document.close();
file.flush();
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am trying to save image and text in pdf file. When we set Either text or image then it's working fine, simultaneously am not able to save image and text Both in pdf. How will I save image and text both in Pdf? I am Using iText.
May the problem is Wrong import for Outputstream and file is Always null . You never assigned any O/P strream.
Try this
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.net.URL;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.pdf.PdfWriter;
public class ItextExample {
#SuppressWarnings("deprecation")
public static void main(String[] args) {
String result = "<html><body><div>(i) the recognised association shall have the approval of the Forward Markets Commission established under the Forward Contracts (Regulation) Act, 1952 (74 of 1952) in respect of trading in derivatives and shall function in accordance with the guidelines or conditions laid down by the Forward Markets Commission; </div> <body> </html>";
Document document = new Document();
OutputStream file = null;
try {
file = new FileOutputStream("E://Image1.pdf");
PdfWriter.getInstance(document,file);
document.open();
HTMLWorker htmlWorker = new HTMLWorker(document);
htmlWorker.parse(new StringReader(result));
String imageUrl = "http://www.taxmann.com/emailer/demo/mobileAapp/newAppDesign.jpg";
Image image2 = Image.getInstance(new URL(imageUrl));
document.add(image2);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
document.close();
file.flush();
}catch(Exception e) {
e.printStackTrace();
}
}
}
}
I'm new to this kabeja package so please can some one provide code example or reading material to render PNG from DXF file using Java?
This is the sample code that generate PNG image from DXF file.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import org.kabeja.dxf.DXFDocument;
import org.kabeja.parser.*;
import org.kabeja.parser.ParserBuilder;
import org.kabeja.svg.SVGGenerator;
import org.kabeja.xml.*;
public class MyClass {
public static void main(String[] args) {
MyClas x=new MyClas();
x.parseFile("C:\\Users\\Space\\Desktop\\test2.dxf");
}
public void parseFile(String sourceFile) {
try {
FileOutputStream o=new FileOutputStream("C:\\Users\\Space\\Desktop\\test2.png");
InputStream in = new FileInputStream(sourceFile);//your stream from upload or somewhere
Parser dxfParser = ParserBuilder.createDefaultParser();
dxfParser.parse(in, "");
DXFDocument doc = dxfParser.getDocument();
SVGGenerator generator = new SVGGenerator();
//org.xml.sax.InputSource out = SAXPNGSerializer;
SAXSerializer out = new org.kabeja.batik.tools.SAXPNGSerializer();
out.setOutput(o);
generator.generate(doc,out,new HashMap());
} catch (ParseException e) {
e.printStackTrace();
} catch (Exception ioe) {
ioe.printStackTrace();
}
}
}
Hope you get what you required :)
Right now i use iText to generate a pdf automatically.
And my problem is that when the content is really very large, i need to calculate the content's height and width, and then add new page...
this is really very inconvinent.
so I wonder whether or not there is a method like:
Document.add("a very very large article");
and after this , it will auto generate a pdf file ????
Thanks in advance !
The following creates a 9 page pdf without having to calculate height and width.
import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
public class HelloWorld {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("HelloWorld.pdf"));
document.open();
String text = "";
for (int i = 0; i < 10000; i++) {
text += "test";
}
document.add(new Paragraph(text));
} catch (DocumentException e) {
System.err.println(e.getMessage());
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
document.close();
}
}
a new page will be generated automaticly, when the content of the current page is full.