【问题标题】:How to create pdf and review in flutter如何在 Flutter 中创建 pdf 和审阅
【发布时间】:2020-01-03 09:19:55
【问题描述】:

我正在尝试创建 pdf 并查看它。

我应用了pdf 插件来创建 pdf ,path_provider 插件用于将 pdf 保存到设备的存储和 flutter_full_pdf_viewer 用于查看pdf的插件。

我已关注create-a-pdf-in-flutter。 但是如果我尝试使用 import 'package:pdf/widgets.dart'; 导入代码中的错误,则材料元素无法正常工作 import 'package:flutter/material.dart';

我做错了什么?

代码:

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:pdf/pdf.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pdfdemo/pages/pdf_viewer.dart';
//import 'package:pdf/widgets.dart'

变量:

final pdf = Document();

创建pdf文件页面:

return Scaffold(
      appBar: AppBar(title: Text("PDF CREATE"),
      actions: <Widget>[
        IconButton(
          icon: Icon(Icons.save),
          onPressed: () => savePdfFile(),
        )
      ],),
      body: pdf.addPage(Page(
      pageFormat: PdfPageFormat.a4,
      build: (BuildContext context) {
        return Center(
          child: Text("Hello Flutter"),
        );
      })),
    );

将 pdf 文件保存到设备的位置:

savePdfFile()async{
    final dir = await getExternalStorageDirectory();
    print("Directoryyyyyyyyy:${dir.path}");
    final String path = "${dir.path}/example.pdf";
    final file = File(path);
    await file.writeAsBytes(pdf.save());
     Navigator.of(context).push(
      MaterialPageRoute(builder: (_) => PgfViewerPage(path: path))
    );
  }

【问题讨论】:

    标签: pdf flutter dart


    【解决方案1】:

    您的代码中的问题是您同时使用材料库和 PDF 库。 PDF 插件提供的小部件在 Flutter 的常规 Scaffold 中不起作用。您可以使用它们构建您的 PDF,就像它们在示例中显示的那样。要获取 PDF 文件,您需要先生成它,然后将其传递到您要显示它的屏幕。

    这样试试,对我有用

            Future<File> createPDF(){
             final Document pdf = Document();
                pdf.addPage(
                    //Your PDF design here with the widget system of the plugin
    MultiPage(
          pageFormat:
              PdfPageFormat.letter.copyWith(marginBottom: 1.5 * PdfPageFormat.cm),
          crossAxisAlignment: CrossAxisAlignment.start,
          theme: Theme(
            tableHeader: TextStyle(fontSize: 8.0),
            tableCell: TextStyle(fontSize: 8.0),
          ),
          header: (Context context) {
            if (context.pageNumber == 1) {
              return null;
            }
            return Container(
                alignment: Alignment.centerRight,
                margin: const EdgeInsets.only(bottom: 3.0 * PdfPageFormat.mm),
                padding: const EdgeInsets.only(bottom: 3.0 * PdfPageFormat.mm),
                decoration: const BoxDecoration(
                    border:
                        BoxBorder(bottom: true, width: 0.5, color: PdfColors.grey)),
                child: Text('VCR',
                    style: Theme.of(context)
                        .defaultTextStyle
                        .copyWith(color: PdfColors.grey)));
          },
        );
    
    
            output = await getTemporaryDirectory();
              final file = File('${output.path}/example.pdf');
              file.writeAsBytesSync(pdf.save());
            return file;
            }
    

    创建 PDF 后,将其显示在如下脚手架中:

    import 'package:flutter/material.dart';
    import 'package:flutter_full_pdf_viewer/full_pdf_viewer_scaffold.dart';
    
    
        class PDFScreen extends StatelessWidget {
          final String pathPDF;
          PDFScreen({this.pathPDF});
    
          @override
          Widget build(BuildContext context) {
            return PDFViewerScaffold(
                appBar: AppBar(
                  title: Text("Document"),
                  actions: <Widget>[
                    IconButton(
                      icon: Icon(Icons.share),
                      onPressed: () {},
                    ),
                  ],
                ),
                path: pathPDF);
          }
        }
    

    调用 file.absolute.path 时从第一个函数获得的 pathPDf

    重要提示:函数和 PDFScreen 必须在不同的文件中!!在您实现生成 PDF 的功能时,您不得导入 'package:flutter/material.dart';

    希望对你有帮助

    【讨论】:

    • 那么先生,您如何以及从哪里调用函数createPDF() 表示来自哪个类?请提供更多代码,我还是不太理解。
    • 在调用 Navigator 函数以转到您的 pdf 查看屏幕之前,您调用 createPDF() 并将文件路径作为 Navigator 的参数
    • 好的,先生,我明白了,但如果我不导入 'package:flutter/material.dart';然后 build() , materialApp() , IconButton() 等将不起作用。
    • 你不应该在同一个文件中调用它们。使用帮助类创建一个新文件,然后在推送导航类之前调用​​它
    • 我使用syncfusion_flutter_pdf: ^18.4.48-beta 创建pdf,然后使用flutter_full_pdf_viewer: ^1.0.6 查看pdf。
    【解决方案2】:
    import 'package:image_gallery_saver/image_gallery_saver.dart';
    import 'package:intl/intl.dart' as intl;
    import 'package:permission_handler/permission_handler.dart';
    import 'package:screenshot/screenshot.dart';
    import 'dart:typed_data';
    import 'package:syncfusion_flutter_pdf/pdf.dart';
    import 'package:path_provider/path_provider.dart';
    import 'package:open_file/open_file.dart';
     // Will take screenshot of the widget and save in Unit8List and create pdf of //Unit8List
        //paste this function where needed
        openPDFofSS();
        //Add controller
         ScreenshotController screenshotController = ScreenshotController();
        //define controller before in widget as
        Screenshot(
      controller: screenshotController,
      child: Text("replace child with the widget you want to convert in pdf"),
    ),
        
        // paste these function 
        
          Future<void> openPDFofSS() async {
            await screenshotController.capture().then((Uint8List image) {
              //Capture Done
              setState(() {
                pdfLoading = true;
                //save screenshot into Uint8List image
                _imageFile = image;
                //convert Unit8List image into PDF
                _convertImageToPDF();
                saveImage(_imageFile);
              });
            }).catchError((onError) {
              print(onError);
            });
          }
        
        
          Future<void> _convertImageToPDF() async {
            //Create the PDF document
            PdfDocument document = PdfDocument();
            //Add the page
            PdfPage page = document.pages.add();
            //Load the image.
            final PdfImage image = PdfBitmap(_imageFile);
            //draw image to the first page
            page.graphics.drawImage(
                image, Rect.fromLTWH(-20, -20, page.size.width - 50, page.size.height));
            //Save the docuemnt
            List<int> bytes = document.save();
            //Dispose the document.
            document.dispose();
            //Get external storage directory
            Directory directory = await getApplicationDocumentsDirectory();
            //Get directory path
            String path = directory.path;
            //Create an empty file to write PDF data
            File file = File('$path/Output.pdf');
        
            //Write PDF data
            await file.writeAsBytes(bytes, flush: true);
            print(path);
            //Open the PDF document in mobile
            OpenFile.open('$path/Output.pdf');
            setState(() {
              pdfLoading = false;
            });
          }
          Future<String> saveImage(Uint8List image) async {
            await [Permission.storage].request();
            final result = await ImageGallerySaver.saveImage(image, name: 'autosmart');
            return result['filePath'];
          }
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2021-10-23
    • 1970-01-01
    • 2019-10-08
    • 2022-01-09
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多