Just My Life & My Work

[Flutter] pdf package

接續上一篇 pdf package 教學文章,已經加入文字,現在我想繼續加入圖片,可以怎麼做呢?🤔

先來看一下顯示截圖~

程式稍微修改:

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pdf/pdf.dart';
import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart';
import 'package:pdf/widgets.dart' as pw;
import 'dart:typed_data';
import 'package:flutter/services.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Happy Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: PdfScreen(),
    );
  }
}

class PdfScreen extends StatefulWidget {
  const PdfScreen({Key key}) : super(key: key);

  @override
  _PdfScreenState createState() => _PdfScreenState();
}

class _PdfScreenState extends State<PdfScreen> {

  String pdfFile = '';
  pw.Document pdf = pw.Document();

  @override
  Widget build(BuildContext context) {
    print('pdfFile: '+pdfFile);

    return Container(
      color: Colors.lightGreen,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Visibility(
            visible: pdfFile.isNotEmpty,
            child: SizedBox(
              width: 300,
              height: 400,
              child: SfPdfViewer.file(File(pdfFile), canShowScrollHead: false, canShowScrollStatus: false,),
            ) ,
          ),
          ElevatedButton(
            onPressed: () {
              createPdfFile();
              savePdfFile();
            },
            child: Text('Create a PDF file'),
          )
        ],
      ),
    );
  }

  Future<void> createPdfFile() async {
    final ByteData bytes = await rootBundle.load('assets/logo_transparent.png');
    final Uint8List byteList = bytes.buffer.asUint8List();

    pdf.addPage(
      pw.MultiPage(
        margin: pw.EdgeInsets.all(10),
        pageFormat: PdfPageFormat.a4,
        build: (pw.Context context) {
          return <pw.Widget> [
            pw.Column(
              crossAxisAlignment: pw.CrossAxisAlignment.start,
              mainAxisSize: pw.MainAxisSize.min,
              children: [
                pw.Text('Create a happy PDF',
                textAlign: pw.TextAlign.center,
                style: pw.TextStyle(fontSize: 28)),
                pw.Divider(),
                for(int i = 0; i < 3; i++)
                  pw.Row(
                    children: [
                      i!=1?pw.Image(
                        pw.MemoryImage(
                          byteList,
                        ),
                        height: 300,
                        width: 200,
                        fit: pw.BoxFit.fitWidth,
                      ):pw.Container(
                        color: PdfColors.blue,
                        height: 300,
                        width: 300,
                      ),
                      i==1?pw.Image(
                        pw.MemoryImage(
                          byteList,
                        ),
                        height: 300,
                        width: 300,
                        fit: pw.BoxFit.fitWidth,
                      ):pw.Container(
                        color: PdfColors.red,
                        height: 300,
                        width: 300,
                      ),
                    ],
                  ),
                pw.Divider(),
              ]
            )
          ];
        }
      )
    );
  }
  void savePdfFile() async {
    Directory documentDirectory = await getApplicationDocumentsDirectory();
    String documentPath = documentDirectory.path;
    String id = DateTime.now().millisecondsSinceEpoch.toString();
    File file = File('$documentPath/$id.pdf');
    file.writeAsBytesSync(await pdf.save());

    setState(() {
      pdfFile = file.path;
      pdf = pw.Document();
    });
  }
}

我將一張 Logo 圖放在專案之中,排版上特地將圖片放兩行,讓圖片可以盡可能呈現在同一頁。

我刻意用迴圈來建立介面,還有展示介面的長與寬。

另外可嘗試改設定,展示 PDF 檔時,可有更多操作功能。

canShowScrollHead: true, canShowScrollStatus: true
.

隨意留個言吧:)~

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com 標誌

您的留言將使用 WordPress.com 帳號。 登出 /  變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 /  變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 /  變更 )

連結到 %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

標籤雲

%d 位部落客按了讚: