【问题标题】:How to convert ByteBuffer to pdf如何将 ByteBuffer 转换为 pdf
【发布时间】:2019-07-19 11:23:19
【问题描述】:

在我的应用程序中,pdf 报告仅在打印预览中打开,允许用户直接打印 pdf 文档。现在我想自动化这个来验证 pdf 内容。

我通过base64中的api获得了pdf内容[确实拆分以仅获取数据],我尝试在解码后转换为字节数组,但它只打印垃圾字符。[字节数组到字符串] 现在我已经将此数据转换为 ByteBuffer 并希望将其写入 pdf。

ByteBuffer decodedBytes = new BASE64Decoder().decodeBufferToByteBuffer(
    new String(base64split2[1].substring(0, base64split2[1].length() - 1))
);

谁能告诉我如何将这个 ByteBuffer 的解码字节转换为 pdf。

谢谢

【问题讨论】:

  • 写入该缓冲区的文件
  • @josejuan 我可以将一个字节写入文件,但是当我尝试写入 bytebuffer 时,我得到了 FileOutputStream 类型中的 write(int) 方法不适用于参数 (ByteBuffer)跨度>
  • 然后查找“如何将ByteBuffer 写入文件”(与应用程序、报告和pdf 无关)参见stackoverflow.com/help/how-to-ask
  • 您可以使用ByteBuffer.array() 转换为字节数组,然后写入该数组。但我不确定这是否是您的问题。
  • 或者你可以在你的字符串上使用Base64.getDecoder().decode(),它会带来一个字节数组。顺便说一句,字符串不需要“新字符串”。

标签: java pdf automation pdfbox bytebuffer


【解决方案1】:
  byte[] decodedBytes = new BASE64Decoder().decodeBuffer(str);
        InputStream targetStream = new ByteArrayInputStream(decodedBytes);
        PDDocument document = PDDocument.load(targetStream);
        document.save("C:/test.pdf");
        FileUtils.writeByteArrayToFile(new File("C:/test.pdf"), decodedBytes);

使用上面的代码转换为pdf。

【讨论】:

  • 你可以直接调用PDDocument.load(decodedBytes),这样速度更快,内存占用也更小。 (因为传递 inputStream 将强制 PDFBox 缓存 - PDFBox 假定 InputStream 是顺序的,PDF 解析需要随机访问)。
【解决方案2】:

从 API 获取 pdf 的 blob 数据:


  Future<dynamic> getBlobdata(int pdfId) async {
    try {
      var response = await Dio().get(
        "https://www.google.com/pdf/$pdfId",
        options: Options(
          responseType: ResponseType.bytes,
          contentType: 'application/octet-stream',
        ),
      );

      var data = {"data": response.data.buffer};
      return data;
    } on DioError catch (error) {
      var data = error.response.data;
      return data;
    }
  }

定义文件名和保存目录:


String fileName = "pdf$pdfId";
final dir = await getExternalStorageDirectory();
var pdfBlob = await getBlobdata(1); // have to be in a asyn func to use await

保存 PDF:


final file = File("${dir.path}/$fileName.pdf");
await file.writeAsBytes(pdfBlob.asUint8List());

在应用中查看 Pdf:


 await OpenFile.open("${dir.path}/$fileName.pdf");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    相关资源
    最近更新 更多