Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PDF background Image not show #154

Closed
1 of 3 tasks
MakSinroja opened this issue Sep 25, 2019 · 4 comments
Closed
1 of 3 tasks

PDF background Image not show #154

MakSinroja opened this issue Sep 25, 2019 · 4 comments

Comments

@MakSinroja
Copy link

Describe the bug
I am trying to add background image for pdf. As per the PDFImage widget requirement, I am convert background image into UInt8List and its converted, but didn't show expected background image and its gave the white background and its doesn't give any error.

Background Image
ic_background_view

My Code
Code snippet to reproduce the behavior:

import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart';
import 'package:example/main.dart';
import 'package:flutter/material.dart' as prefix0;
import 'package:flutter/services.dart';

class PDFCreatorWidget {
  String fileName = 'background_demo.pdf';

  PdfDocument _generateDocument() {
    final pdf = new PdfDocument(deflate: zlib.encode);
    final page = new PdfPage(pdf, pageFormat: PdfPageFormat.a4);
    final g = page.getGraphics();
    g.setColor(new PdfColor(0.0, 1.0, 1.0));
    g.setColor(new PdfColor(0.3, 0.3, 0.3));
    return pdf;
  }

  Future<PdfImage> pdfImageFromImage({PdfDocument pdf, ui.Image image}) async {
    final ByteData bytes =
    await image.toByteData(format: ui.ImageByteFormat.rawRgba);

    return PdfImage(
      pdf,
      image: bytes.buffer.asUint8List(),
      width: PdfPageFormat.a4.width.toInt(),
      height: PdfPageFormat.a4.height.toInt(),
    );
  }

  Future<PdfImage> pdfImageFromImageProvider(
      {PdfDocument pdf,
        prefix0.ImageProvider image,
        prefix0.ImageConfiguration configuration,
        prefix0.ImageErrorListener onError}) async {
    final Completer<PdfImage> completer = Completer<PdfImage>();
    final prefix0.ImageStream stream =
    image.resolve(configuration ?? prefix0.ImageConfiguration.empty);

    prefix0.ImageStreamListener listener;
    listener =
        prefix0.ImageStreamListener((prefix0.ImageInfo image, bool sync) async {
          final PdfImage result =
          await pdfImageFromImage(pdf: pdf, image: image.image);
          if (!completer.isCompleted) {
            completer.complete(result);
          }
          stream.removeListener(listener);
        }, onError: (dynamic exception, StackTrace stackTrace) {
          if (!completer.isCompleted) {
            completer.complete(null);
          }
          if (onError != null) {
            onError(exception, stackTrace);
          } else {
            // https://groups.google.com/forum/#!topic/flutter-announce/hp1RNIgej38
            assert(false, 'image failed to load');
          }
        });

    stream.addListener(listener);
    return completer.future;
  }

  Future<String> createPDF() async {
    final Document pdf = Document();
    final PdfDocument pdfDocument = _generateDocument();

    const imageProvider = const prefix0.AssetImage('assets/ic_background_view.png');
    final PdfImage pdfImage =
    await pdfImageFromImageProvider(pdf: pdfDocument, image: imageProvider);

    pdf.addPage(
      MultiPage(
        crossAxisAlignment: CrossAxisAlignment.start,
        pageTheme: PageTheme(
          buildBackground: (context) {
            return Container(
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: pdfImage,
                  fit: BoxFit.cover,
                ),
              ),
              child: Container(),
            );
          },
          pageFormat: PdfPageFormat.a4,
        ),
        header: (Context context) {
          return null;
        },
        footer: (Context context) {
          return Container(
            alignment: Alignment.centerRight,
            child: Text(
              '${context.pageNumber} / ${context.pagesCount}',
              textAlign: TextAlign.right,
              style: TextStyle(
                color: PdfColors.grey,
              ),
            ),
          );
        },
        build: (Context context) => <Widget>[
          Container(child: Text('Background Image Demo')),
        ],
      ),
    );

    String filePath;

    await getApplicationDocumentsDirectory().then((directory) async {
      filePath = directory.path;
    });

    Directory pdfDirectory;

    await Directory('$filePath/PDFs')
        .exists()
        .then((isExistsDirectory) async {
      if (isExistsDirectory) {
        pdfDirectory = Directory('$filePath/PDFs');
      } else {
        await Directory('$filePath/PDFs')
            .create()
            .then((createdDirectory) {
          pdfDirectory = createdDirectory;
        });
      }
    });

    final File file = File('${pdfDirectory.path}/$fileName');
    file.writeAsBytesSync(pdf.save());
    return file.path;
  }
}

Expected behavior
I want to add background image into pdf background.(i.e. same as like watermark)

Flutter Doctor

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel master, v1.10.6-pre.59, on Linux, locale en_GB.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[✓] Chrome - develop for the web
[✓] Android Studio (version 3.5)
[✓] Android Studio (version 3.4)
[✓] Connected device (3 available)

Desktop (please complete the following information):

  • iOS
  • Android
  • Browser
@MakSinroja MakSinroja changed the title Background Image not show PDF background Image not show Sep 25, 2019
@DavBfr
Copy link
Owner

DavBfr commented Sep 25, 2019

You cannot use width: PdfPageFormat.a4.width.toInt() and height: PdfPageFormat.a4.height.toInt(), for the size. It must be the exact pixel dimentions of the RGBA buffer you pass. Please use the provided functions pdfImageFromImage and pdfImageFromImageProvider They work as expected.

Your code:

DecorationImage(
                  image: pdfImage,
                  fit: BoxFit.cover,
                ),

will take care to stretch the image to fill the page, keeping the aspect ratio.

@MakSinroja
Copy link
Author

Sir, I have already used pdfImageFromImage and pdfImageFromImageProvider functions into the code but still couldn't show the background image.

And as per your suggestion, I have changed the width and height (414x815) which is exact pixel dimensions of the RGBA buffer I am passing, but it wan't work.

@DavBfr
Copy link
Owner

DavBfr commented Sep 26, 2019

ok, replace the line

final PdfDocument pdfDocument = _generateDocument();

with

final PdfDocument pdfDocument = pdf.document;

and Buy Me A Coffee.

@MakSinroja
Copy link
Author

Thank you for helping me and its worked.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants