flutter capture the widget to image and then create PDF file to printer









up vote
0
down vote

favorite












My flutter app captures the widget to image and then creates PDF file to printer, but it shows ridiculous result as below picture.



Let me know if you have any better method to print Chinese character and qr image to a receipt (bluetooth printer with paper width 75mm)



Here with the widget:



RepaintBoundary(
key: _renderObjectKey,
child: ListView(
children: <Widget>[
Form(
key: tableNumberFormKey,
child:
ListTile(
title: TextFormField(
initialValue: "",
style: TextStyle(fontSize: 48.0),
textAlign: TextAlign.center,
maxLength: 4,
keyboardType: TextInputType.phone,
onSaved: (val) => inputTableNumber = val.toString(),
validator: (val) => val.isEmpty ? '' : null,
decoration: new InputDecoration(
labelText: "輸入檯號",
hintText: "例如:12",
),
),
),
),
FlatButton(
textColor: Colors.blueAccent,
child: Text(
"列印 QR CODE",
style: TextStyle(fontWeight: FontWeight.w500, fontSize: 20.0),
),
color: Colors.transparent,
onPressed: ()
_showQRandPrint();
SystemChannels.textInput.invokeMethod('TextInput.hide');
,
),
inputTableNumber == ""
? ListTile(title: Text(''),)
: Center(
child: QrImage(
data: qrString,
size: 300.0,
version: 10,
backgroundColor: Colors.white,
),
),

],
),
);


Here with the function to create image and pdf to printer.



void _showQRandPrint() 
final FormState form = tableNumberFormKey.currentState;

if (form.validate())
form.save();

_getWidgetImage().then((img)
final pdf = new PDFDocument();
final page = new PDFPage(pdf, pageFormat: PDFPageFormat(75.0, 100.0));
final g = page.getGraphics();
final font = new PDFFont(pdf);

PDFImage image = new PDFImage(
pdf,
image: img,
width: 75,
height: 100);
g.drawImage(image, 0.0, 0.0);

Printing.printPdf(document: pdf);
);


else
setState(()
inputTableNumber = "";
);



Future<Uint8List> _getWidgetImage() async
try
RenderRepaintBoundary boundary =
_renderObjectKey.currentContext.findRenderObject();
ui.Image image = await boundary.toImage(pixelRatio: 3.0);
ByteData byteData =
await image.toByteData(format: ui.ImageByteFormat.png);
var pngBytes = byteData.buffer.asUint8List();
var bs64 = base64Encode(pngBytes);
debugPrint(bs64.length.toString());
return pngBytes;
catch (exception)



result picture preview:



enter image description here



The widget on the screen is:



enter image description here










share|improve this question



























    up vote
    0
    down vote

    favorite












    My flutter app captures the widget to image and then creates PDF file to printer, but it shows ridiculous result as below picture.



    Let me know if you have any better method to print Chinese character and qr image to a receipt (bluetooth printer with paper width 75mm)



    Here with the widget:



    RepaintBoundary(
    key: _renderObjectKey,
    child: ListView(
    children: <Widget>[
    Form(
    key: tableNumberFormKey,
    child:
    ListTile(
    title: TextFormField(
    initialValue: "",
    style: TextStyle(fontSize: 48.0),
    textAlign: TextAlign.center,
    maxLength: 4,
    keyboardType: TextInputType.phone,
    onSaved: (val) => inputTableNumber = val.toString(),
    validator: (val) => val.isEmpty ? '' : null,
    decoration: new InputDecoration(
    labelText: "輸入檯號",
    hintText: "例如:12",
    ),
    ),
    ),
    ),
    FlatButton(
    textColor: Colors.blueAccent,
    child: Text(
    "列印 QR CODE",
    style: TextStyle(fontWeight: FontWeight.w500, fontSize: 20.0),
    ),
    color: Colors.transparent,
    onPressed: ()
    _showQRandPrint();
    SystemChannels.textInput.invokeMethod('TextInput.hide');
    ,
    ),
    inputTableNumber == ""
    ? ListTile(title: Text(''),)
    : Center(
    child: QrImage(
    data: qrString,
    size: 300.0,
    version: 10,
    backgroundColor: Colors.white,
    ),
    ),

    ],
    ),
    );


    Here with the function to create image and pdf to printer.



    void _showQRandPrint() 
    final FormState form = tableNumberFormKey.currentState;

    if (form.validate())
    form.save();

    _getWidgetImage().then((img)
    final pdf = new PDFDocument();
    final page = new PDFPage(pdf, pageFormat: PDFPageFormat(75.0, 100.0));
    final g = page.getGraphics();
    final font = new PDFFont(pdf);

    PDFImage image = new PDFImage(
    pdf,
    image: img,
    width: 75,
    height: 100);
    g.drawImage(image, 0.0, 0.0);

    Printing.printPdf(document: pdf);
    );


    else
    setState(()
    inputTableNumber = "";
    );



    Future<Uint8List> _getWidgetImage() async
    try
    RenderRepaintBoundary boundary =
    _renderObjectKey.currentContext.findRenderObject();
    ui.Image image = await boundary.toImage(pixelRatio: 3.0);
    ByteData byteData =
    await image.toByteData(format: ui.ImageByteFormat.png);
    var pngBytes = byteData.buffer.asUint8List();
    var bs64 = base64Encode(pngBytes);
    debugPrint(bs64.length.toString());
    return pngBytes;
    catch (exception)



    result picture preview:



    enter image description here



    The widget on the screen is:



    enter image description here










    share|improve this question

























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      My flutter app captures the widget to image and then creates PDF file to printer, but it shows ridiculous result as below picture.



      Let me know if you have any better method to print Chinese character and qr image to a receipt (bluetooth printer with paper width 75mm)



      Here with the widget:



      RepaintBoundary(
      key: _renderObjectKey,
      child: ListView(
      children: <Widget>[
      Form(
      key: tableNumberFormKey,
      child:
      ListTile(
      title: TextFormField(
      initialValue: "",
      style: TextStyle(fontSize: 48.0),
      textAlign: TextAlign.center,
      maxLength: 4,
      keyboardType: TextInputType.phone,
      onSaved: (val) => inputTableNumber = val.toString(),
      validator: (val) => val.isEmpty ? '' : null,
      decoration: new InputDecoration(
      labelText: "輸入檯號",
      hintText: "例如:12",
      ),
      ),
      ),
      ),
      FlatButton(
      textColor: Colors.blueAccent,
      child: Text(
      "列印 QR CODE",
      style: TextStyle(fontWeight: FontWeight.w500, fontSize: 20.0),
      ),
      color: Colors.transparent,
      onPressed: ()
      _showQRandPrint();
      SystemChannels.textInput.invokeMethod('TextInput.hide');
      ,
      ),
      inputTableNumber == ""
      ? ListTile(title: Text(''),)
      : Center(
      child: QrImage(
      data: qrString,
      size: 300.0,
      version: 10,
      backgroundColor: Colors.white,
      ),
      ),

      ],
      ),
      );


      Here with the function to create image and pdf to printer.



      void _showQRandPrint() 
      final FormState form = tableNumberFormKey.currentState;

      if (form.validate())
      form.save();

      _getWidgetImage().then((img)
      final pdf = new PDFDocument();
      final page = new PDFPage(pdf, pageFormat: PDFPageFormat(75.0, 100.0));
      final g = page.getGraphics();
      final font = new PDFFont(pdf);

      PDFImage image = new PDFImage(
      pdf,
      image: img,
      width: 75,
      height: 100);
      g.drawImage(image, 0.0, 0.0);

      Printing.printPdf(document: pdf);
      );


      else
      setState(()
      inputTableNumber = "";
      );



      Future<Uint8List> _getWidgetImage() async
      try
      RenderRepaintBoundary boundary =
      _renderObjectKey.currentContext.findRenderObject();
      ui.Image image = await boundary.toImage(pixelRatio: 3.0);
      ByteData byteData =
      await image.toByteData(format: ui.ImageByteFormat.png);
      var pngBytes = byteData.buffer.asUint8List();
      var bs64 = base64Encode(pngBytes);
      debugPrint(bs64.length.toString());
      return pngBytes;
      catch (exception)



      result picture preview:



      enter image description here



      The widget on the screen is:



      enter image description here










      share|improve this question















      My flutter app captures the widget to image and then creates PDF file to printer, but it shows ridiculous result as below picture.



      Let me know if you have any better method to print Chinese character and qr image to a receipt (bluetooth printer with paper width 75mm)



      Here with the widget:



      RepaintBoundary(
      key: _renderObjectKey,
      child: ListView(
      children: <Widget>[
      Form(
      key: tableNumberFormKey,
      child:
      ListTile(
      title: TextFormField(
      initialValue: "",
      style: TextStyle(fontSize: 48.0),
      textAlign: TextAlign.center,
      maxLength: 4,
      keyboardType: TextInputType.phone,
      onSaved: (val) => inputTableNumber = val.toString(),
      validator: (val) => val.isEmpty ? '' : null,
      decoration: new InputDecoration(
      labelText: "輸入檯號",
      hintText: "例如:12",
      ),
      ),
      ),
      ),
      FlatButton(
      textColor: Colors.blueAccent,
      child: Text(
      "列印 QR CODE",
      style: TextStyle(fontWeight: FontWeight.w500, fontSize: 20.0),
      ),
      color: Colors.transparent,
      onPressed: ()
      _showQRandPrint();
      SystemChannels.textInput.invokeMethod('TextInput.hide');
      ,
      ),
      inputTableNumber == ""
      ? ListTile(title: Text(''),)
      : Center(
      child: QrImage(
      data: qrString,
      size: 300.0,
      version: 10,
      backgroundColor: Colors.white,
      ),
      ),

      ],
      ),
      );


      Here with the function to create image and pdf to printer.



      void _showQRandPrint() 
      final FormState form = tableNumberFormKey.currentState;

      if (form.validate())
      form.save();

      _getWidgetImage().then((img)
      final pdf = new PDFDocument();
      final page = new PDFPage(pdf, pageFormat: PDFPageFormat(75.0, 100.0));
      final g = page.getGraphics();
      final font = new PDFFont(pdf);

      PDFImage image = new PDFImage(
      pdf,
      image: img,
      width: 75,
      height: 100);
      g.drawImage(image, 0.0, 0.0);

      Printing.printPdf(document: pdf);
      );


      else
      setState(()
      inputTableNumber = "";
      );



      Future<Uint8List> _getWidgetImage() async
      try
      RenderRepaintBoundary boundary =
      _renderObjectKey.currentContext.findRenderObject();
      ui.Image image = await boundary.toImage(pixelRatio: 3.0);
      ByteData byteData =
      await image.toByteData(format: ui.ImageByteFormat.png);
      var pngBytes = byteData.buffer.asUint8List();
      var bs64 = base64Encode(pngBytes);
      debugPrint(bs64.length.toString());
      return pngBytes;
      catch (exception)



      result picture preview:



      enter image description here



      The widget on the screen is:



      enter image description here







      printing flutter






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Oct 31 at 19:16









      James Z

      11.1k71735




      11.1k71735










      asked Oct 31 at 18:13









      GPH

      12912




      12912






















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          Few errors:




          • PDFPageFormat(75.0, 100.0) is in pdf native dimensions. If you want milimeters, do:



            PDFPageFormat(75.0 * PDFPageFormat.MM, 100.0 * PDFPageFormat.MM)


          • When you declare an image, you have to pass the pixel size



          • And the image cannot be png, but rawRgba data:



            // var img = await image.toByteData(format: ui.ImageByteFormat.rawRgba);
            PDFImage image = new PDFImage(
            pdf,
            image: img.buffer.asUint8List(),
            width: img.width,
            height: img.height);



          • the pdf coordinate system has 0,0 at the bottom left corner of the page and still in pdf units
            so you have to use:



            g.drawImage(image, 100.0 * PDFPageFormat.MM, 0.0, 75.0* PDFPageFormat.MM);


            the third parameter set the width. the height is calculated to keep the aspect ratio.



            maybe you will have to adapt this to center the image, but there is an example on the library page.







          share|improve this answer




















          • Thank you very much! it works well.
            – GPH
            Nov 11 at 16:05










          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53089690%2fflutter-capture-the-widget-to-image-and-then-create-pdf-file-to-printer%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          1
          down vote



          accepted










          Few errors:




          • PDFPageFormat(75.0, 100.0) is in pdf native dimensions. If you want milimeters, do:



            PDFPageFormat(75.0 * PDFPageFormat.MM, 100.0 * PDFPageFormat.MM)


          • When you declare an image, you have to pass the pixel size



          • And the image cannot be png, but rawRgba data:



            // var img = await image.toByteData(format: ui.ImageByteFormat.rawRgba);
            PDFImage image = new PDFImage(
            pdf,
            image: img.buffer.asUint8List(),
            width: img.width,
            height: img.height);



          • the pdf coordinate system has 0,0 at the bottom left corner of the page and still in pdf units
            so you have to use:



            g.drawImage(image, 100.0 * PDFPageFormat.MM, 0.0, 75.0* PDFPageFormat.MM);


            the third parameter set the width. the height is calculated to keep the aspect ratio.



            maybe you will have to adapt this to center the image, but there is an example on the library page.







          share|improve this answer




















          • Thank you very much! it works well.
            – GPH
            Nov 11 at 16:05














          up vote
          1
          down vote



          accepted










          Few errors:




          • PDFPageFormat(75.0, 100.0) is in pdf native dimensions. If you want milimeters, do:



            PDFPageFormat(75.0 * PDFPageFormat.MM, 100.0 * PDFPageFormat.MM)


          • When you declare an image, you have to pass the pixel size



          • And the image cannot be png, but rawRgba data:



            // var img = await image.toByteData(format: ui.ImageByteFormat.rawRgba);
            PDFImage image = new PDFImage(
            pdf,
            image: img.buffer.asUint8List(),
            width: img.width,
            height: img.height);



          • the pdf coordinate system has 0,0 at the bottom left corner of the page and still in pdf units
            so you have to use:



            g.drawImage(image, 100.0 * PDFPageFormat.MM, 0.0, 75.0* PDFPageFormat.MM);


            the third parameter set the width. the height is calculated to keep the aspect ratio.



            maybe you will have to adapt this to center the image, but there is an example on the library page.







          share|improve this answer




















          • Thank you very much! it works well.
            – GPH
            Nov 11 at 16:05












          up vote
          1
          down vote



          accepted







          up vote
          1
          down vote



          accepted






          Few errors:




          • PDFPageFormat(75.0, 100.0) is in pdf native dimensions. If you want milimeters, do:



            PDFPageFormat(75.0 * PDFPageFormat.MM, 100.0 * PDFPageFormat.MM)


          • When you declare an image, you have to pass the pixel size



          • And the image cannot be png, but rawRgba data:



            // var img = await image.toByteData(format: ui.ImageByteFormat.rawRgba);
            PDFImage image = new PDFImage(
            pdf,
            image: img.buffer.asUint8List(),
            width: img.width,
            height: img.height);



          • the pdf coordinate system has 0,0 at the bottom left corner of the page and still in pdf units
            so you have to use:



            g.drawImage(image, 100.0 * PDFPageFormat.MM, 0.0, 75.0* PDFPageFormat.MM);


            the third parameter set the width. the height is calculated to keep the aspect ratio.



            maybe you will have to adapt this to center the image, but there is an example on the library page.







          share|improve this answer












          Few errors:




          • PDFPageFormat(75.0, 100.0) is in pdf native dimensions. If you want milimeters, do:



            PDFPageFormat(75.0 * PDFPageFormat.MM, 100.0 * PDFPageFormat.MM)


          • When you declare an image, you have to pass the pixel size



          • And the image cannot be png, but rawRgba data:



            // var img = await image.toByteData(format: ui.ImageByteFormat.rawRgba);
            PDFImage image = new PDFImage(
            pdf,
            image: img.buffer.asUint8List(),
            width: img.width,
            height: img.height);



          • the pdf coordinate system has 0,0 at the bottom left corner of the page and still in pdf units
            so you have to use:



            g.drawImage(image, 100.0 * PDFPageFormat.MM, 0.0, 75.0* PDFPageFormat.MM);


            the third parameter set the width. the height is calculated to keep the aspect ratio.



            maybe you will have to adapt this to center the image, but there is an example on the library page.








          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 11 at 12:58









          Dav

          261




          261











          • Thank you very much! it works well.
            – GPH
            Nov 11 at 16:05
















          • Thank you very much! it works well.
            – GPH
            Nov 11 at 16:05















          Thank you very much! it works well.
          – GPH
          Nov 11 at 16:05




          Thank you very much! it works well.
          – GPH
          Nov 11 at 16:05

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53089690%2fflutter-capture-the-widget-to-image-and-then-create-pdf-file-to-printer%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          這個網誌中的熱門文章

          Barbados

          How to read a connectionString WITH PROVIDER in .NET Core?

          Node.js Script on GitHub Pages or Amazon S3