先 通过 httpclient 请求 得到 pdf相关的字节数组,而后,把字节数组转成 pdf文件,再 把 pdf 转成 jpg,再 以压缩包 的形式,输出到页面,
这个问题搞一天了,没搞出来,谁做过,帮我看一下,我贴一下源码:
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
byte[] body = EntityUtils.toByteArray(entity);
getFile(body, null);
pdfToJpg(savePath, zos, i);
}
public static void pdfToJpg(String getPdfFilePath, ZipOutputStream zos, int i) throws IOException {
String savePath = "F:\\" +"test.pdf";
File file = new File(savePath);
// load a pdf from a byte buffer
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdffile = new PDFFile(buf);
// draw the first page to an image
PDFPage page = pdffile.getPage(1);
// get the width and height for the doc at the default zoom
Rectangle rect = new Rectangle(0, 0, (int) page.getBBox().getWidth(), (int) page.getBBox().getHeight());
// generate the image
Image img = page.getImage(rect.width, rect.height, // width &
// height
rect, // clip rect
null, // null for the ImageObserver
true, // fill background with white
true // block until drawing is done
);
BufferedImage tag = new BufferedImage(rect.width, rect.height, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(img, 0, 0, rect.width, rect.height, null);
File jpgFile = new File("F:\\" +"test.jpg");
FileOutputStream out = new FileOutputStream(jpgFile); // 输出到文件流
ZipEntry entry = new ZipEntry("report"+i+".jpg");
zos.putNextEntry(entry);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag); // JPEG编码
ImageIO.write(tag, "jpg", zos);
out.close();
// raf.close();
// channel.close();
}
/**
* 根据byte数组,生成文件
*/
public static void getFile(byte[] bfile, String savePath) {
String filePath = "F:\\" +"test.pdf";
FileOutputStream fos = null;
BufferedOutputStream bos = null;
File file = null;
try {
file = new File(filePath);
fos = new FileOutputStream(filePath);
bos = new BufferedOutputStream(fos);
bos.write(bfile);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}