1、首先將上傳的非jpg,pdf格式的文件轉成pdf,這個是采用OpenOffice進行轉的,具體代碼如下:
private void officeToPdf(){
OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
try {
connection.connect();
} catch (ConnectException e) {
e.printStackTrace();
}
DocumentConverter converter = new OpenOfficeDocumentConverter(
connection);
converter.convert(officeFile, pdfFile);
// close the connection
connection.disconnect();
}
2、然后將pdf首頁轉為jpg,具體代碼如下:
private ?void pdfToJPG(String inputFile) throws IOException { // load a pdf from a byte buffer File file = new File(inputFile); 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); for (int i = 1; i <= pdffile.getNumPages(); i++) { if (i == 1) { // draw the first page to an image // 以圖片的形式來描繪首頁 PDFPage page = pdffile.getPage(i); // 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); FileOutputStream out = new FileOutputStream( imagePath+"\\"+fileName.substring(fileName.lastIndexOf("/")+1) + ".jpg"); // 輸出到文件流 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(tag); // JPEG編碼 // 關閉輸出流 out.close(); System.out.println("PDF文件轉換JPG文件成功"); } }