Ладно, отвечю сам себе:
Код |
import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException;
import javax.imageio.ImageIO;
import multivalent.Behavior; import multivalent.Browser; import multivalent.Context; import multivalent.Document; import multivalent.Multivalent; import multivalent.Node; import multivalent.ParseException; import multivalent.node.Root; import multivalent.std.adaptor.pdf.PDF; import phelps.io.Files; import phelps.util.Units;
public class Pdf2Image { public static BufferedImage getPageBild(String pdfFilePath, int pageNr )throws IOException, ParseException { Browser br = Multivalent.getInstance().getBrowser("fake"); PDF pdf = (PDF) Behavior.getInstance("AdobePDF", "AdobePDF", null, null, null); File file = Files.getFile(pdfFilePath); pdf.setFile(file); Root root = br.getRoot(); Document doc = new Document("doc", null, root); pdf.docURI = file.toURI();
pdf.parse(doc); // empty parse to determine page count int pagecnt = Integer.parseInt(doc.getAttr(Document.ATTR_PAGECOUNT)); doc.clear(); doc.putAttr(Document.ATTR_PAGE, Integer.toString(pageNr)); pdf.parse(doc); Node top = doc.childAt(0); doc.formatBeforeAfter(0, 0, null); int w = top.bbox.width; int h = top.bbox.height; BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g = img.createGraphics(); g.setClip(0, 0, w, h);
// paint page g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); Context cx = doc.getStyleSheet().getContext(g, Toolkit.getDefaultToolkit(), null); top.paintBeforeAfter(g.getClipBounds(), cx);
// clean up doc.removeAllChildren(); cx.reset(); g.dispose(); pdf.getReader().close(); return img; } public static BufferedImage CropImage(BufferedImage img, int xll, int yll, int xur, int yur) { img = img.getSubimage(xll, yur, xur-xll, yll-yur); return img; }
}
|
|