使用 Java 将 PDF 页面导出为一系列图像

2024-03-29

我需要将任意 PDF 文档的页面导出为 jpeg/png/etc 格式的一系列单独图像。我需要在 Java 中执行此操作。

虽然我确实了解 iText、PDFBox 和各种其他 java pdf 库,但我希望能找到一些工作示例或一些操作方法。

Thanks.


这是一种方法,结合来自网络的一些代码片段。

如何将 PDF 绘制为图像?

https://pdf-renderer.dev.java.net/examples.html http://java.net/projects/pdf-renderer

从图像创建缓冲图像

原来的:http://www.exampledepot.com/egs/java.awt.image/Image2Buf.html http://www.exampledepot.com/egs/java.awt.image/Image2Buf.html

更新:如何将缓冲图像转换为图像,反之亦然? https://stackoverflow.com/questions/9132149/how-to-convert-buffered-image-to-image-and-vice-versa

将生成的图形保存为 PNG 或 JPEG 文件

原来的:http://www.exampledepot.com/egs/javax.imageio/Graphic2File.html http://www.exampledepot.com/egs/javax.imageio/Graphic2File.html

更新:http://docs.oracle.com/javase/tutorial/2d/images/saveimage.html http://docs.oracle.com/javase/tutorial/2d/images/saveimage.html

组合在一起,就像这样将所有页面变成图像:

import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;

import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Transparency;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import javax.swing.*;
import javax.imageio.*;
import java.awt.image.*;

public class ImageMain {
    public static void setup() throws IOException {
        // load a pdf from a byte buffer
        File file = new File("test.pdf");
        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 numPgs = pdffile.getNumPages();
        for (int i = 0; i < numPgs; i++) {
            // 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
                    );
            // save it as a file
            BufferedImage bImg = toBufferedImage(img);
            File yourImageFile = new File("page_" + i + ".png");
            ImageIO.write(bImg, "png", yourImageFile);
        }
    }

    // This method returns a buffered image with the contents of an image
    public static BufferedImage toBufferedImage(Image image) {
        if (image instanceof BufferedImage) {
            return (BufferedImage) image;
        }
        // This code ensures that all the pixels in the image are loaded
        image = new ImageIcon(image).getImage();
        // Determine if the image has transparent pixels; for this method's
        // implementation, see e661 Determining If an Image Has Transparent
        // Pixels
        boolean hasAlpha = hasAlpha(image);
        // Create a buffered image with a format that's compatible with the
        // screen
        BufferedImage bimage = null;
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        try {
            // Determine the type of transparency of the new buffered image
            int transparency = Transparency.OPAQUE;
            if (hasAlpha) {
                transparency = Transparency.BITMASK;
            }
            // Create the buffered image
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
        } catch (HeadlessException e) {
            // The system does not have a screen
        }
        if (bimage == null) {
            // Create a buffered image using the default color model
            int type = BufferedImage.TYPE_INT_RGB;
            if (hasAlpha) {
                type = BufferedImage.TYPE_INT_ARGB;
            }
            bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
        }
        // Copy image to buffered image
        Graphics g = bimage.createGraphics();
        // Paint the image onto the buffered image
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return bimage;
    }

    public static boolean hasAlpha(Image image) {
        // If buffered image, the color model is readily available
        if (image instanceof BufferedImage) {
            BufferedImage bimage = (BufferedImage) image;
            return bimage.getColorModel().hasAlpha();
        }
        // Use a pixel grabber to retrieve the image's color model;
        // grabbing a single pixel is usually sufficient
        PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
        try {
            pg.grabPixels();
        } catch (InterruptedException e) {
        }
        // Get the image's color model
        ColorModel cm = pg.getColorModel();
        return cm.hasAlpha();
    }

    public static void main(final String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                try {
                    ImageMain.setup();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Java 将 PDF 页面导出为一系列图像 的相关文章

  • JSF:初始请求和回发请求?

    请看一下 JSF 中的下面这行代码
  • JFace DialogCellEditor:如何使按钮始终出现?

    我用的是JFaceDialogCellEditor在 JFace 的一行单元格中显示一个按钮TableViewer激活时会触发一个对话框 此行为适用于以下代码 但仅当显式选择托管按钮的表的单元格时才会显示该按钮 public class C
  • 使用 window.print 内容将网页下载为 pdf

    我想要一个链接 当单击该链接时 会自动开始下载网页的可打印版本 我正在使用Moodle 我想要的内容是完全相同的如果我使用 ctrl p 下载页面并保存为 pdf 或使用 a href Download web page a 我正是想要该内
  • Jersey 2 - ContainerRequestFilter get 方法注解

    我试图获取 ContainerRequestFilter 对象中的方法注释 控制器 GET RolesAllowed ADMIN public String message return Hello rest12 容器请求过滤器 Provi
  • 加载 XSLT 文件时解析相对路径

    我需要使用 Apache FOP 进行 XSL 转换 我的代码如下 Setup FOP Fop fop fopFactory newFop MimeConstants MIME PDF out Setup Transformer Sourc
  • Ant 复制文件而不覆盖

    Is there any command in ant to copy files from one folder structure to another without checking the last modified date t
  • Spring中需要多个相同类型的bean

    将其标记为重复之前的请求 我浏览了论坛 但在任何地方都找不到该问题的解决方案 我正在使用 Spring 3 2 编写代码 一切都是纯粹基于注释的 该代码接收从不同 XSD 文件派生的 XML 文件 所以我们可以说 有五个不同的 XSD A1
  • JUnit 测试 Spymemcached 客户端

    我有一个类围绕spymemcached 客户端 我想编写一些JUnit 测试来测试getValue 和addKey 方法是否有效 问题是无法从测试服务器访问spymemcached 服务器 所以我想这里需要一些模拟 我的简化类看起来像这样
  • 配置 logback 以遵循 Java 配置,即 Logback 的纯 Java 配置

    我只是不喜欢 Logback 的 XML 或 Groovy 配置 更喜欢用 Java 进行配置 这也是因为我将在初始化后的不同时间在运行时更改配置 似乎对 Logback 进行 Java 配置的唯一方法是进行某种初始化劫持根追加器 http
  • Android Studio 1.0.1 APK META-INF/DEPENDENCIES 中复制的重复文件

    我安装了 Android Studio 版本 1 0 1 并尝试将我的项目从 eclipse 导入到它 它给了我以下错误 Error Execution failed for task app packageDebug Duplicate
  • Hibernate 在更新集合时删除孤儿

    我发现从 Hibernate 中的集合中删除时 孤立记录不会被删除 我一定是做了一些简单的错误 这是 Hibernate 101 但我找不到它 鉴于以下情况 public class Book ManyToOne NotNull Autho
  • 在 Java 中从 Json 字符串中提取字段

    我正在尝试从以下 Json 字符串中提取每个 company id 的 id String test company id 4100 data drm user id 572901936637129135 direct status id
  • LDAP中超时的实现

    我一直在处理我们正在使用的应用程序LDAP获取用户详细信息 有时获取用户详细信息需要更多时间 我想实施time out获取详细信息的方法 以便我们可以避免在最坏的情况下在服务器中挂起事务 这里我们使用的是LdapUtil我们在其中配置的类L
  • 如何使用 Java 以编程方式登录 Facebook?

    我正在尝试编写一个可以自动登录 Facebook 的 Java 程序 到目前为止 我已经得到了以下代码 可以将主页 html 页面下载到字符串中 但不知道如何发送电子邮件和密码来登录 Facebook Java 程序还需要处理返回的 coo
  • java中的new关键字是多余的吗?

    我来自 C 所以 java 的一个特性我不太理解 我读过所有对象都必须使用关键字创建new 但基元除外 现在 如果编译器可以识别原始类型 并且不允许您在不调用其构造函数的情况下创建对象new 有这个关键字的原因是什么new根本吗 有人可以提
  • 当将 Eclipse 与 FindBugs 一起使用时,您可以将错误标记为非错误并将其从错误列表中删除吗?

    FindBugs 在我的代码中发现了潜在的错误 但这不是一个错误 是否可以将此事件标记为 不是错误 并将其从错误列表中删除 我已经非常清楚地记录了为什么每种情况都不是错误 例如 类实现类似的接口 它有compareTo方法 然而 我没有重写
  • 使用 getPathMatcher 的全局模式

    从 OCP 考试的 Kathy Sierra Bert Bates 书中我找到了以下代码 public class FileTest public static void matches Path path String glob Path
  • Spring-WS WSDL生成问题

    我正在尝试制作一个非常简单的 Web 服务 但在让 spring 生成正确的 wsdl 时遇到一些困难 我已尽力复制此示例春季教程 http static springsource org spring ws sites 2 0 refer
  • Android 中的 RoboSpice 库是什么

    我正在尝试了解 android 中的 RoboSpice 库 我在这里看到了在线文档 https github com stephanenicolas robospice wiki Starter Guide 我尝试过什么 我之前研究过使用
  • 在 Maven Shade 插件中包含依赖项

    我正在尝试使用 Apache 的 commons lang3 创建一个可部署的 jar 但是 我的 Hadoop 所在的 AWS 集群不包含此库 因此我收到了 classNotFoundException 我想我需要手动添加该依赖项 但我在

随机推荐