1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| public static void main(String[] args) throws IOException { File officeFile = new File("D:/test.doc"); File pdfFile = new File("D:/test.pdf"); officeToPdf(officeFile, pdfFile); pdfToJPG("D:/test.pdf", "D:/"); }
private static void officeToPdf(File officeFile, File pdfFile) { OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100); try { connection.connect(); DocumentConverter converter = new OpenOfficeDocumentConverter( connection); converter.convert(officeFile, pdfFile); } catch (ConnectException e) { e.printStackTrace(); } finally { connection.disconnect(); } }
private static void pdfToJPG(String pdfPath, String imagePath) throws IOException { File file = new File(pdfPath);
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); int totalPage = pdffile.getNumPages(); for (int i = 1; i <= totalPage; i++) { if (i == 1) { PDFPage page = pdffile.getPage(i); Rectangle rect = new Rectangle(0, 0, (int) page.getBBox() .getWidth(), (int) page.getBBox().getHeight());
Image img = page.getImage(rect.width, rect.height, rect, null, true, true ); BufferedImage tag = new BufferedImage(rect.width, rect.height, BufferedImage.TYPE_INT_RGB); tag.getGraphics().drawImage(img.getScaledInstance(rect.width, rect.height, Image.SCALE_SMOOTH), 0, 0, rect.width, rect.height, null);
FileOutputStream out = new FileOutputStream(imagePath + File.separator + pdfPath.substring(pdfPath.lastIndexOf("/") + 1, pdfPath.lastIndexOf(".")) + ".jpg"); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(tag); out.close(); break; } } buf.clear(); channel.close(); raf.close(); unmap(buf); }
public static <T> void unmap(final Object buffer) { AccessController.doPrivileged(new PrivilegedAction<T>() { @Override public T run() { try { Method getCleanerMethod = buffer.getClass().getMethod("cleaner", new Class[0]); getCleanerMethod.setAccessible(true); Cleaner cleaner = (sun.misc.Cleaner) getCleanerMethod.invoke(buffer, new Object[0]); cleaner.clean(); } catch (Exception e) { e.printStackTrace(); } return null; } }); }
|