Using flying saucer convert html to Image - java

Using flying saucer, i successfully convert html to image using below code
//doc - html source code as org.w3c.dom.Document
Java2DRenderer renderer = new Java2DRenderer(doc, width, height);
BufferedImage img = renderer.getImage();
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", os);
But i have problems in the above code like it does not render the font properly in the html.
Also if the chinese ,Japanese or other than Ascii characters given, the image has not been rendered with proper content(characters are boxed like below).
But actual html content is
<div ><ul><li><dl><dt>イベントについて<br></dt><dd><ul><li>サポーター&フレンズ<br></li></ul></dd></dl><dl><dt>イベント・セミナー一覧<br></dt></dl></li></ul><div><br></div></div>
Also in my case, any language will come, but all encoded using unicode. How to solve this.
Please help.

String html = "<div ><ul><li><dl><dt>イベントについて<br></dt><dd><ul><li>サポーター&フレンズ<br></li></ul></dd></dl><dl><dt>イベント・セミナー一覧<br></dt></dl></li></ul><div><br></div></div>"
//Read it using Utf-8 - Based on encoding, change the encoding name if you know it
InputStream htmlStream = new ByteArrayInputStream(html.getBytes("UTF-8"));
Tidy tidy = new Tidy();
org.w3c.dom.Document doc = tidy.parseDOM(new InputStreamReader(htmlStream,"UTF-8"), null);
Java2DRenderer renderer = new Java2DRenderer(doc, width, height);
BufferedImage img = renderer.getImage();
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", os);
This solves my issue. On reading html stream using UTF-8 solves the issue.

Related

Download image from SVG with Jersey

I have some SVG string from highcharts and I want to download it as an image (PNG).
The conversion is done using PNGTranscoder (Batik)
#POST
public Response getChartImage() throws Exception{
String svg = "<svg xmlns:xlink..."; // can be ignored
svg = svgDocumentConvertAndRevert(svg); // can be ignored
TranscoderInput input = new TranscoderInput(new StringReader(svg));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
TranscoderOutput output = new TranscoderOutput(baos);
PNGTranscoder transcoder = new PNGTranscoder();
transcoder.transcode(input, output);
BufferedImage image = new BufferedImage(300, 500, 1);
ImageIO.write(image, "png", baos);
byte[] imageData = baos.toByteArray();
return Response.ok(imageData).build();
}
but what I'm getting is a bunch of text, something like
�PNG IHDR�#��E� cHRMz&��...
Tried with #Produces("image/*") but didn't work...
Can I not save it as an image (real file) and allow user to download it? Trying to avoid unnecessary effort..
Thanks!
You need to set the correct mime type for the response something like
response.setContentType("image/png");
where response is a ServletResponse object.
It was working, just that I was using Chrome's extension POSTman.

convert all images to PNG

I need a dynamic solution to convert a unknown image format to .png in java.
Will .getType() help me out here, it seems only to return numbers.
The converted image should later be stored in a folder, but I guess that is easly done in the
ImageIO.write().
It's just that with converting an unknown image format that I have no idea how to approach.
This peace of code should do the magic:
File file = new File("unknown.type.pic");
ByteArrayInputStream bais = new ByteArrayInputStream(FileUtils.readFileToByteArray(file);
BufferedImage image = ImageIO.read(bais);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);
OutputStream outputStream = new FileOutputStream ("output.jpg");
baos.writeTo(outputStream);
Add missing try/catch/finally blocks.

Write CMYK image in PDF

I need to add a CMYK Image (java.awt.BufferedImage) to a Pdf-Document with iText.
I'm trying to do it with:
com.lowagie.text.Image img = Image.getInstance(BufferedImage, bgColor);
This produces an RGB image in the resulting PDF. (and I suppose it's a bug, because it just ignores ColorModel). However I could use:
com.lowagie.text.Image img = Image.getInstance(byte[] rawData);
And it produces a correct CMYK-Image in PDF. But for the second case I need to convert java.awt.BufferedImage in ByteArray. I cannot do it with ImageIO.write(ByteArrayOutputStream). I also cannot do it with com.sun.image.codec.jpeg.JPEGImageEncoder because I must use OpenJDK.
Any ideas how can I achieve the correct behavior to write a CMYK image in PDF using iText?
So basically what you're asking is how to convert a BufferedImage to a byte[] to print to PDF?
BufferedImage img; // your image to be printed
String formatName; // name of the image format (see ImageIO docs)
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( img, formatName, baos);
byte[] rawData = baos.toByteArray();
You should be able to use that for the CMYK-image as you had in your original post:
com.lowagie.text.Image img = Image.getInstance(byte[] rawData);

convert html to image in byte array java

How can i easily convert html to image and then to byte array without create it
thanks
If you do not have any complex html you can render it using a normal JLabel. The code below will produce this image:
<html>
<h1>:)</h1>
Hello World!<br>
<img src="http://img0.gmodules.com/ig/images/igoogle_logo_sm.png">
</html>
public static void main(String... args) throws IOException {
String html = "<html>" +
"<h1>:)</h1>" +
"Hello World!<br>" +
"<img src=\"http://img0.gmodules.com/ig/images/igoogle_logo_sm.png\">" +
"</html>";
JLabel label = new JLabel(html);
label.setSize(200, 120);
BufferedImage image = new BufferedImage(
label.getWidth(), label.getHeight(),
BufferedImage.TYPE_INT_ARGB);
{
// paint the html to an image
Graphics g = image.getGraphics();
g.setColor(Color.BLACK);
label.paint(g);
g.dispose();
}
// get the byte array of the image (as jpeg)
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);
byte[] bytes = baos.toByteArray();
....
}
If you would like to just write it to a file:
ImageIO.write(image, "png", new File("test.png"));
I think you can use the library
html2image-0.9.jar
you can download this library at this page: http://code.google.com/p/java-html2image/
What about using an in memory ByteArrayStream instead of a FileOutputStream in the code above? That would be a byte array, at least ...
This is nontrivial because rendering a HTML page can be quite complex: you have text, images, CSS, possibly even JavaScript to evaluate.
I don't know the answer, but I do have something that might help you: code for iText (a PDF writing library) to convert a HTML page to a PDF file.
public static final void convert(final File xhtmlFile, final File pdfFile) throws IOException, DocumentException
{
final String xhtmlUrl = xhtmlFile.toURI().toURL().toString();
final OutputStream reportPdfStream = new FileOutputStream(pdfFile);
final ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(xhtmlUrl);
renderer.layout();
renderer.createPDF(reportPdfStream);
reportPdfStream.close();
}

xhtmlrenderer xhtml to pdf font problem

I'm using org.xhtmlrenderer.pdf.ITextRenderer to convert my (x)html page to pdf using Java.
I've got most of it working, except the font part.
I'm using verdana in my page and the pdf is rendered using default font.
I have added the verdana.ttf to my jar and use the following code:
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new StringBufferInputStream(html));
File tmpFontFile = new File(TEMP_FOLDER + "/verdana.ttf");
if(!tmpFontFile.exists())
{
tmpFontFile.createNewFile();
InputStream fontIs = getClass().getResourceAsStream("/com/mycompany/util/font/verdana.ttf");
OutputStream fontOs = new FileOutputStream(tmpFontFile);
byte buf[] = new byte[1024];
int len;
while((len = fontIs.read(buf)) > 0)
fontOs.write(buf,0,len);
fontOs.close();
fontIs.close();
}
ITextRenderer renderer = new ITextRenderer();
renderer.getFontResolver().addFont(
tmpFontFile.getAbsolutePath(), BaseFont.IDENTITY_H ,BaseFont.EMBEDDED);
renderer.setDocument(doc, null);
String outputFile = TEMP_FOLDER + "/mypdf.pdf";
OutputStream os = new FileOutputStream(outputFile);
renderer.layout();
renderer.createPDF(os);
os.close();
What am I missing here?
Thanks,
Bart
For xhtmlrenderer to work, the CSS must read:
font-family: Verdana;
instead of
font-family:verdana;
It's case-sensitive.

Categories

Resources