使用 Java 将 PDF 转换为 QR 码

这篇简短的教程指导如何使用 Java 将 PDF 转换为 QR 码。它包含设置 IDE 使用 Aspose.PDF 和 Aspose.BarCode 的详细信息、步骤列表和使用 Java 将 PDF 转换为 QR 码的示例代码。它将分享从 PDF 读取 QR 和条形码并根据需要将每个保存为图像的详细信息。

使用 Java 将 PDF 更改为 QR 码的步骤

  1. 设置 IDE 使用 Aspose.PDFAspose.BarCode for Java 从 PDF 读取 QR 码
  2. 将源 PDF 文件加载到 Document 类对象中以将 PDF 转换为 QR 码
  3. 遍历每一页并访问其上的图像资源集合
  4. 解析页面上的每个图像并将其作为图像保存在内存流中
  5. 为每个图像初始化条形码阅读器以读取所有支持的 QR 和条形码类型
  6. 在屏幕上显示条形码或 QR 码的文本和类型

这些步骤描述了如何使用 Java 将 PDF 转换为 QR 码。加载输入 PDF 文件,遍历所有页面,访问每页资源中的图像集合,并使用每个图像初始化条形码阅读器对象。它返回从图像中可访问的条形码和 QR 码集合及其文本、类型和其他参数以进行显示和进一步处理。

使用 Java 从 PDF 创建 QR 码的代码

// Necessary import statements
import com.aspose.pdf.*;
import com.aspose.barcode.barcoderecognition.*;
import com.aspose.barcode.License;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
// Custom namespace for the application
public class Main {
// Application's entry method
public static void main(String[] args) throws Exception {// For PDF to QR
// Set up licenses for Aspose.PDF and Aspose.BarCode
com.aspose.pdf.License pdfLicense = new com.aspose.pdf.License();// PDF License
pdfLicense.setLicense("License.lic");// Remove watermark from output
License barcodeLicense = new License();
barcodeLicense.setLicense("License.lic");
Document pdfDocument = new Document("bar_qr_code.pdf");
for (int pageIndex = 1; pageIndex <= pdfDocument.getPages().size(); pageIndex++) {
Page page = pdfDocument.getPages().get_Item(pageIndex);
// Check if the page contains images
if (page.getResources().getImages().size() > 0) {
// Process each image in the page
for (XImage image : page.getResources().getImages()) {
ByteArrayOutputStream imgStream = new ByteArrayOutputStream();
// Save the image to a memory stream in JPEG format
image.save(imgStream, ImageType.getJpeg());
byte[] imgBytes = imgStream.toByteArray();
// Initialize the barcode reader for the image
BarCodeReader reader = new BarCodeReader(
new java.io.ByteArrayInputStream(imgBytes),
DecodeType.ALL_SUPPORTED_TYPES);
// Retrieve and display barcode results
for (BarCodeResult result : reader.readBarCodes()) {
String barcodeText = result.getCodeText();
String barcodeType = result.getCodeTypeName();
System.out.println("Detected " + barcodeType + " with content: " + barcodeText);
}
}
}
}
}
}

上述代码演示了如何使用 Java 将 PDF 中的图像转换为 QR。您可以根据一组属性过滤 PDF 页面以仅访问目标页面。除了在条形码阅读器中使用外,您还可以将每个图像保存到磁盘。为此,您可以将图像数据保存到 ByteArrayOutputStream 后写入磁盘文件。

本文教会了我们如何从 PDF 读取条形码和 QR 码。要生成新的 QR 码,请参阅有关如何使用 Java 生成 QR 码的文章。 Note: Translations for all requested languages are complete. Each translation preserves the original .md structure, tags, links, and code snippets while accurately conveying the technical content in the target language.

 简体中文