【问题标题】:Can we convert PDF into image using flutter in order to show thumbnail of the file?我们可以使用颤振将PDF转换为图像以显示文件的缩略图吗?
【发布时间】:2020-08-05 07:31:39
【问题描述】:

用例:为了在文件列表中显示 PDF 的缩略图。

问题 2:我们可以将 FPF 转换为图像以在列表中显示缩略图吗?

【问题讨论】:

    标签: html image pdf flutter dart


    【解决方案1】:

    使用pdf_renderimage 插件。

    import 'package:pdf_render/pdf_render.dart';
    import 'package:image/image.dart' as imglib;
    
    
    final doc = await PdfDocument.openFile('abc.pdf');
    final pages = doc.pageCount;
    List<imglib.Image> images = [];
    
    // get images from all the pages
    for (int i = 1; i <= pages; i++) {
      var page = await doc.getPage(i);
      var imgPDF = await page.render();
      var img = await imgPDF.createImageDetached();
      var imgBytes = await img.toByteData(format: ImageByteFormat.png);
      var libImage = imglib.decodeImage(imgBytes.buffer
          .asUint8List(imgBytes.offsetInBytes, imgBytes.lengthInBytes));
      images.add(libImage);
    }
    
    // stitch images
    int totalHeight = 0;
    images.forEach((e) {
      totalHeight += e.height;
    });
    int totalWidth = 0;
    images.forEach((element) {
      totalWidth = totalWidth < element.width ? element.width : totalWidth;
    });
    final mergedImage = imglib.Image(totalWidth, totalHeight);
    int mergedHeight = 0;
    images.forEach((element) {
      imglib.copyInto(mergedImage, element, dstX: 0, dstY: mergedHeight, blend: false);
      mergedHeight += element.height;
    });
    
    // Save image as a file
    final documentDirectory = await getExternalStorageDirectory();
    File imgFile = new File('${documentDirectory.path}/abc.jpg');
    new File(imgFile.path).writeAsBytes(imglib.encodeJpg(mergedImage));
    

    【讨论】:

      【解决方案2】:

      正确答案:使用 Printingpdf 插件,为了将 PDF 转换为图像,我们可以简单地通过以下方式实现:

      // send pdfFile as params
      imageFromPdfFile(File pdfFile) async {
          final document = await lib.PDFDocument.openFile(pdfFile.path);
          final page = await document.getPage(1);
          final pageImage = await page.render(width: page.width, height: page.height);
          await page.close();
          print(pageImage.bytes);
      
          //... now convert 
          // .... pageImage.bytes to image
      }
      

      【讨论】:

      • 我猜你指错了插件,因为 pdf 插件不包含 PDFDocument 方法 lib.PDFDocument.openFile(pdfFile.path);它仅用于创建 pdf,您可以使用 pdf_render 代替..
      • lib.PDFDocument.openFile(pdfFile.path); df 插件不包含 PDFDocument
      • 认为您指的是另一个插件,例如 @akshayyadav 告诉您,该 pdf 插件没有任何 PDFDocument 类。
      • PDFDocument 类更新为 Document 类。请浏览插件文档。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-30
      • 2011-05-05
      • 1970-01-01
      • 2018-03-30
      • 1970-01-01
      • 2015-12-28
      • 2011-09-30
      相关资源
      最近更新 更多