如何在Flutter中创建PDF并进行审阅。

huangapple go评论127阅读模式
英文:

How to create pdf and review in flutter

问题

I'm trying to create pdf and review it.

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

I applied pdf plugin for creating the pdf, path_provider plugin for save the pdf to the device's storage and flutter_full_pdf_viewer plugin for view the pdf.

我使用 pdf 插件创建 PDF,使用 path_provider 插件将 PDF 保存到设备存储中,使用 flutter_full_pdf_viewer 插件查看 PDF。

I have followed create-a-pdf-in-flutter.
But getting errors in the code if I try to import with import 'package:pdf/widgets.dart';, material element isn't working import 'package:flutter/material.dart';.

我遵循了 create-a-pdf-in-flutter。但是,如果我尝试导入 import 'package:pdf/widgets.dart';,代码会出现错误,Material 元素无法工作 import 'package:flutter/material.dart';

What am I doing wrong?

我做错了什么?

Code:

  1. import 'dart:io';
  2. import 'package:flutter/material.dart';
  3. import 'package:pdf/pdf.dart';
  4. import 'package:path_provider/path_provider.dart';
  5. import 'package:pdfdemo/pages/pdf_viewer.dart';
  6. //import 'package:pdf/widgets.dart'

Variable:

  1. final pdf = Document();

Creating pdf file page:

  1. return Scaffold(
  2. appBar: AppBar(title: Text("PDF CREATE"),
  3. actions: <Widget>[
  4. IconButton(
  5. icon: Icon(Icons.save),
  6. onPressed: () => savePdfFile(),
  7. )
  8. ],),
  9. body: pdf.addPage(Page(
  10. pageFormat: PdfPageFormat.a4,
  11. build: (BuildContext context) {
  12. return Center(
  13. child: Text("Hello Flutter"),
  14. );
  15. })),
  16. );

Saving pdf file to the device's location:

  1. savePdfFile()async{
  2. final dir = await getExternalStorageDirectory();
  3. print("Directoryyyyyyyyy:${dir.path}");
  4. final String path = "${dir.path}/example.pdf";
  5. final file = File(path);
  6. await file.writeAsBytes(pdf.save());
  7. Navigator.of(context).push(
  8. MaterialPageRoute(builder: (_) => PgfViewerPage(path: path))
  9. );
  10. }
英文:

I'm trying to create pdf and review it.

I applied pdf plugin for creating the pdf , path_provider plugin for save the pdf to the device's storage and
flutter_full_pdf_viewer plugin for view the pdf.

I have followed create-a-pdf-in-flutter.
But getting errors in the code if I try to import with import &#39;package:pdf/widgets.dart&#39;; , material element isn't working import &#39;package:flutter/material.dart&#39;; .

如何在Flutter中创建PDF并进行审阅。

What am I doing wrong?

Code:

  1. import &#39;dart:io&#39;;
  2. import &#39;package:flutter/material.dart&#39;;
  3. import &#39;package:pdf/pdf.dart&#39;;
  4. import &#39;package:path_provider/path_provider.dart&#39;;
  5. import &#39;package:pdfdemo/pages/pdf_viewer.dart&#39;;
  6. //import &#39;package:pdf/widgets.dart&#39;

Variable:

  1. final pdf = Document();

Creating pdf file page:

  1. return Scaffold(
  2. appBar: AppBar(title: Text(&quot;PDF CREATE&quot;),
  3. actions: &lt;Widget&gt;[
  4. IconButton(
  5. icon: Icon(Icons.save),
  6. onPressed: () =&gt; savePdfFile(),
  7. )
  8. ],),
  9. body: pdf.addPage(Page(
  10. pageFormat: PdfPageFormat.a4,
  11. build: (BuildContext context) {
  12. return Center(
  13. child: Text(&quot;Hello Flutter&quot;),
  14. );
  15. })),
  16. );

Saving pdf file to the device's location:

  1. savePdfFile()async{
  2. final dir = await getExternalStorageDirectory();
  3. print(&quot;Directoryyyyyyyyy:${dir.path}&quot;);
  4. final String path = &quot;${dir.path}/example.pdf&quot;;
  5. final file = File(path);
  6. await file.writeAsBytes(pdf.save());
  7. Navigator.of(context).push(
  8. MaterialPageRoute(builder: (_) =&gt; PgfViewerPage(path: path))
  9. );
  10. }

答案1

得分: 1

你的代码中的问题是你同时使用了Material库和PDF库。PDF插件提供的小部件在普通的Flutter Scaffold中无法正常工作。你需要像示例中展示的那样使用PDF插件构建PDF。要获取PDF文件,你需要首先生成它,然后将它传递到你想要显示它的屏幕上。

可以尝试以下方式,这对我有用:

  1. Future<File> createPDF() {
  2. final Document pdf = Document();
  3. pdf.addPage(
  4. // 在此处使用插件的小部件系统设计你的PDF
  5. MultiPage(
  6. pageFormat: PdfPageFormat.letter.copyWith(marginBottom: 1.5 * PdfPageFormat.cm),
  7. crossAxisAlignment: CrossAxisAlignment.start,
  8. theme: Theme(
  9. tableHeader: TextStyle(fontSize: 8.0),
  10. tableCell: TextStyle(fontSize: 8.0),
  11. ),
  12. header: (Context context) {
  13. if (context.pageNumber == 1) {
  14. return null;
  15. }
  16. return Container(
  17. alignment: Alignment.centerRight,
  18. margin: const EdgeInsets.only(bottom: 3.0 * PdfPageFormat.mm),
  19. padding: const EdgeInsets.only(bottom: 3.0 * PdfPageFormat.mm),
  20. decoration: const BoxDecoration(
  21. border: BoxBorder(bottom: true, width: 0.5, color: PdfColors.grey),
  22. ),
  23. child: Text('VCR', style: Theme.of(context).defaultTextStyle.copyWith(color: PdfColors.grey)),
  24. );
  25. },
  26. ),
  27. );
  28. output = await getTemporaryDirectory();
  29. final file = File('${output.path}/example.pdf');
  30. file.writeAsBytesSync(pdf.save());
  31. return file;
  32. }

在创建了PDF之后,可以像这样在Scaffold中显示它:

  1. import 'package:flutter/material.dart';
  2. import 'package:flutter_full_pdf_viewer/full_pdf_viewer_scaffold.dart';
  3. class PDFScreen extends StatelessWidget {
  4. final String pathPDF;
  5. PDFScreen({this.pathPDF});
  6. @override
  7. Widget build(BuildContext context) {
  8. return PDFViewerScaffold(
  9. appBar: AppBar(
  10. title: Text("Document"),
  11. actions: <Widget>[
  12. IconButton(
  13. icon: Icon(Icons.share),
  14. onPressed: () {},
  15. ),
  16. ],
  17. ),
  18. path: pathPDF,
  19. );
  20. }
  21. }

从第一个函数中获取pathPDF,只需调用file.absolute.path

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

希望这对你有所帮助。

英文:

The Problem in your code is that you are using the material library and the PDF library at the same time. The Widgets that are provided by the PDF plugin dont work in the regular Scaffold from flutter. You build your PDF with them like they are showing in the example. To get the PDF file you need to generate it first and then pass it to the screen where you wanna display it.

Try it like this, it worked for me

  1. Future&lt;File&gt; createPDF(){
  2. final Document pdf = Document();
  3. pdf.addPage(
  4. //Your PDF design here with the widget system of the plugin
  5. MultiPage(
  6. pageFormat:
  7. PdfPageFormat.letter.copyWith(marginBottom: 1.5 * PdfPageFormat.cm),
  8. crossAxisAlignment: CrossAxisAlignment.start,
  9. theme: Theme(
  10. tableHeader: TextStyle(fontSize: 8.0),
  11. tableCell: TextStyle(fontSize: 8.0),
  12. ),
  13. header: (Context context) {
  14. if (context.pageNumber == 1) {
  15. return null;
  16. }
  17. return Container(
  18. alignment: Alignment.centerRight,
  19. margin: const EdgeInsets.only(bottom: 3.0 * PdfPageFormat.mm),
  20. padding: const EdgeInsets.only(bottom: 3.0 * PdfPageFormat.mm),
  21. decoration: const BoxDecoration(
  22. border:
  23. BoxBorder(bottom: true, width: 0.5, color: PdfColors.grey)),
  24. child: Text(&#39;VCR&#39;,
  25. style: Theme.of(context)
  26. .defaultTextStyle
  27. .copyWith(color: PdfColors.grey)));
  28. },
  29. );
  30. output = await getTemporaryDirectory();
  31. final file = File(&#39;${output.path}/example.pdf&#39;);
  32. file.writeAsBytesSync(pdf.save());
  33. return file;
  34. }

After you created the PDF display it in a scaffold like this:

  1. import &#39;package:flutter/material.dart&#39;;
  2. import &#39;package:flutter_full_pdf_viewer/full_pdf_viewer_scaffold.dart&#39;;
  3. class PDFScreen extends StatelessWidget {
  4. final String pathPDF;
  5. PDFScreen({this.pathPDF});
  6. @override
  7. Widget build(BuildContext context) {
  8. return PDFViewerScaffold(
  9. appBar: AppBar(
  10. title: Text(&quot;Document&quot;),
  11. actions: &lt;Widget&gt;[
  12. IconButton(
  13. icon: Icon(Icons.share),
  14. onPressed: () {},
  15. ),
  16. ],
  17. ),
  18. path: pathPDF);
  19. }
  20. }

the pathPDf you get from the first function if you call file.absolute.path

IMPORTANT: the function and the PDFScreen must be in separate files!! Where you implement the function for generating the PDF you MUST NOT import 'package:flutter/material.dart';

hope this helps

答案2

得分: 0

  1. import 'package:image_gallery_saver/image_gallery_saver.dart';
  2. import 'package:intl/intl.dart' as intl;
  3. import 'package:permission_handler/permission_handler.dart';
  4. import 'package:screenshot/screenshot.dart';
  5. import 'dart:typed_data';
  6. import 'package:syncfusion_flutter_pdf/pdf.dart';
  7. import 'package:path_provider/path_provider.dart';
  8. import 'package:open_file/open_file.dart';
  9. // 将小部分代码翻译,不包括注释和函数名
  10. // 导入必要的包
  11. import 'package:image_gallery_saver/image_gallery_saver.dart';
  12. import 'package:intl/intl.dart' as intl;
  13. import 'package:permission_handler/permission_handler.dart';
  14. import 'package:screenshot/screenshot.dart';
  15. import 'dart:typed_data';
  16. import 'package:syncfusion_flutter_pdf/pdf.dart';
  17. import 'package:path_provider/path_provider.dart';
  18. import 'package:open_file/open_file.dart';
  19. // 将小部分代码翻译,不包括注释和函数名
  20. ScreenshotController screenshotController = ScreenshotController();
  21. Screenshot(
  22. controller: screenshotController,
  23. child: Text("替换 child 为要转换成 PDF 的小部件"),
  24. );
  25. Future<void> openPDFofSS() async {
  26. await screenshotController.capture().then((Uint8List image) {
  27. setState(() {
  28. pdfLoading = true;
  29. _imageFile = image;
  30. _convertImageToPDF();
  31. saveImage(_imageFile);
  32. });
  33. }).catchError((onError) {
  34. print(onError);
  35. });
  36. }
  37. Future<void> _convertImageToPDF() async {
  38. PdfDocument document = PdfDocument();
  39. PdfPage page = document.pages.add();
  40. final PdfImage image = PdfBitmap(_imageFile);
  41. page.graphics.drawImage(
  42. image, Rect.fromLTWH(-20, -20, page.size.width - 50, page.size.height));
  43. List<int> bytes = document.save();
  44. document.dispose();
  45. Directory directory = await getApplicationDocumentsDirectory();
  46. String path = directory.path;
  47. File file = File('$path/Output.pdf');
  48. await file.writeAsBytes(bytes, flush: true);
  49. print(path);
  50. OpenFile.open('$path/Output.pdf');
  51. setState(() {
  52. pdfLoading = false;
  53. });
  54. }
  55. Future<String> saveImage(Uint8List image) async {
  56. await [Permission.storage].request();
  57. final result = await ImageGallerySaver.saveImage(image, name: 'autosmart');
  58. return result['filePath'];
  59. }
英文:
  1. import &#39;package:image_gallery_saver/image_gallery_saver.dart&#39;;
  2. import &#39;package:intl/intl.dart&#39; as intl;
  3. import &#39;package:permission_handler/permission_handler.dart&#39;;
  4. import &#39;package:screenshot/screenshot.dart&#39;;
  5. import &#39;dart:typed_data&#39;;
  6. import &#39;package:syncfusion_flutter_pdf/pdf.dart&#39;;
  7. import &#39;package:path_provider/path_provider.dart&#39;;
  8. import &#39;package:open_file/open_file.dart&#39;;
  9. // Will take screenshot of the widget and save in Unit8List and create pdf of //Unit8List
  10. //paste this function where needed
  11. openPDFofSS();
  12. //Add controller
  13. ScreenshotController screenshotController = ScreenshotController();
  14. //define controller before in widget as
  15. Screenshot(
  16. controller: screenshotController,
  17. child: Text(&quot;replace child with the widget you want to convert in pdf&quot;),
  18. ),
  19. // paste these function
  20. Future&lt;void&gt; openPDFofSS() async {
  21. await screenshotController.capture().then((Uint8List image) {
  22. //Capture Done
  23. setState(() {
  24. pdfLoading = true;
  25. //save screenshot into Uint8List image
  26. _imageFile = image;
  27. //convert Unit8List image into PDF
  28. _convertImageToPDF();
  29. saveImage(_imageFile);
  30. });
  31. }).catchError((onError) {
  32. print(onError);
  33. });
  34. }
  35. Future&lt;void&gt; _convertImageToPDF() async {
  36. //Create the PDF document
  37. PdfDocument document = PdfDocument();
  38. //Add the page
  39. PdfPage page = document.pages.add();
  40. //Load the image.
  41. final PdfImage image = PdfBitmap(_imageFile);
  42. //draw image to the first page
  43. page.graphics.drawImage(
  44. image, Rect.fromLTWH(-20, -20, page.size.width - 50, page.size.height));
  45. //Save the docuemnt
  46. List&lt;int&gt; bytes = document.save();
  47. //Dispose the document.
  48. document.dispose();
  49. //Get external storage directory
  50. Directory directory = await getApplicationDocumentsDirectory();
  51. //Get directory path
  52. String path = directory.path;
  53. //Create an empty file to write PDF data
  54. File file = File(&#39;$path/Output.pdf&#39;);
  55. //Write PDF data
  56. await file.writeAsBytes(bytes, flush: true);
  57. print(path);
  58. //Open the PDF document in mobile
  59. OpenFile.open(&#39;$path/Output.pdf&#39;);
  60. setState(() {
  61. pdfLoading = false;
  62. });
  63. }
  64. Future&lt;String&gt; saveImage(Uint8List image) async {
  65. await [Permission.storage].request();
  66. final result = await ImageGallerySaver.saveImage(image, name: &#39;autosmart&#39;);
  67. return result[&#39;filePath&#39;];
  68. }

huangapple
  • 本文由 发表于 2020年1月3日 17:19:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/59575888.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定