java - iTextPdf not loading Images correctly -
heyo, have problem piece of code:
private void createpdf(string[] url, string name) throws filenotfoundexception, documentexception, ioexception{ com.itextpdf.text.document document = new com.itextpdf.text.document(); fileoutputstream fos = new fileoutputstream(name); pdfwriter writer = pdfwriter.getinstance(document, fos); writer.open(); document.open(); document.setmargins(1, 0, 0, 0); document.addtitle(name); document.addsubject(name); (string url1 : url) { image = image.getinstance(new java.net.url(url1)); i.scaletofit(document.getpagesize()); document.add(i); document.newpage(); writer.flush(); } document.close(); writer.close(); }
the images jpeg formatted , on server using itext-pdfa-5.5.5 itext-xtra-5.5.5 via maven.
the problem is, pictures not displayed correctly cut in halve. how can prevent happen?
what tried until now:
- what see above
- preloading image imageio
both same result.
please me.
okay inserted (with getimage beeing bruno lowagies code below)
bufferedimage read = imageio.read(new bytearrayinputstream(getimage(new java.net.url(url1)))); imageio.write(read, "jpeg", new file(url1.substring(url1.length()-8, url1.length()))); image = image.getinstance(read, null);
and files arent downloaded , bottom part of picture seems filled #808080
itext doesn't change singe byte of jpg image. takes bytes receives , puts them inside pdf in stream defining /filter
/dctdecode
, there should no problem importing jpg images.
however, looking @ code, see expect image
object load file url: new java.net.url(url1)
, remember people having problems similar yours because inputstream
obtained url
object wasn't read when url1
wasn't file url, url image on web.
this problem inherent reading inputstream
s: image
needs read first bytes of inputstream
first determine image type, , go start of inputstream
read full image.
to work around problem, better read image byte[]
first , use byte[]
parameter image
constructor.
something this:
public byte[] getimage(url url) throws ioexception { bytearrayoutputstream baos = new bytearrayoutputstream(); inputstream = url.openstream (); byte[] b = new byte[4096]; int n; while ( (n = is.read(b)) > -1 ) { baos.write(b, 0, n); } return baos.tobytearray(); }
and then:
image = image.getinstance(getimage(new java.net.url(url1)));
i wrote these code snippets without testing. please let me know if work (or update answer if made typos).
Comments
Post a Comment