Search code examples
htmlioscssflutterpdf-generation

Unable to remove the page outer margin of the pdf which is created using html/css in flutter iOS


I am trying to remove the outer white margin of PDF which is created using Html/css in flutter-iOS-app. In case of android the layout is working fine but incase of iOS there is left-margin issue as shown in the attachment of iOS.

Issue at Github using DartPdf: Issue at DartPdf

Issue at Github using flutter_html_to_pdf: Issue at flutter_html_to_pdf

I have used these libraries in order to convert and render html to pdf.

pubspec.yaml

dev_dependencies:
  flutter_test:
    sdk: flutter
  pdf: ^1.3.17
  printing: ^2.0.0
  flutter_full_pdf_viewer: ^1.0.4

Method to print html as PDF:

Future<void> printPdfMethod() async {
  print('Print ...');
  await Printing.layoutPdf(onLayout: (PdfPageFormat format) async {
    return await Printing.convertHtml(
        format: PdfPageFormat.a4
            .applyMargin(left: 0, top: 0, right: 0, bottom: 0),
        html:
            '<?xml version="1.0"?> <html> <head> <title>CSS Template</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> @page { size: A4; margin: 0mm 0mm 0mm 0mm; padding:0mm 0mm 0mm 0mm; } body { margin: 0px; padding: 0px; position: static; width:100%; height:100%; } </style> </head> <body style="margin:0;padding:10" bgcolor="#144434"> <h1 style="color:white">Test Layout Margin</h1></body> </html>');
  });
}

style-property: Using this property the margin issue resolves in android but still not working on iOS case.

@page {
        size: A4;
        margin: 0mm 0mm 0mm 0mm;
    }

body {
        margin: 0px;
        padding: 0px;
    }

Android Screenshot:

enter image description here

iOS Screenshot:

enter image description here

Required Result: The pdf will only contain the dark green layout and remove that outer white spacing in both iOS and android.

Note(When 2 or more pages): Incase of iOS when using this format property (format: PdfPageFormat.a4 .applyMargin(left: 0, top: 0, right: 0, bottom: 0)), when the PDF splits the some of the views or data are invisible or hidden.


Solution

  • Finally this will resolve the issue of printing:

    We have to set the margin using copyWith(..). applyMargin(..) will only increase the margin from what you already have. And you also have to use the provided paper format:

    await Printing.layoutPdf(onLayout: (PdfPageFormat format) async {
      return await Printing.convertHtml(
          format: format.copyWith(marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0),
          html: '<?xml version="1.0"?><html><body style="margin:0;padding:0" bgcolor="#144434"><h1 style="color:white">Test Layout Margin</h1></body></html>');
    });