unit8ToPdf function

void unit8ToPdf(
  1. Uint8List imageBytes,
  2. String url,
  3. String refCode, {
  4. bool showLoading = false,
})

Implementation

void unit8ToPdf(Uint8List imageBytes, String url, String refCode,  {bool showLoading = false}) async {
  final pdf = pw.Document();

  const pageFormat = PdfPageFormat.a4;
  final pageHeight = pageFormat.availableHeight;
  final pageWidth = pageFormat.availableWidth;

  final image = pw.MemoryImage(imageBytes);
  final imageWidth = (image.width ?? 0).toDouble();
  final imageHeight = (image.height ?? 0).toDouble();

  final imageAspectRatio = imageWidth / imageHeight;
  double scaledWidth;
  double scaledHeight;

  if (imageAspectRatio > 1) {
    scaledWidth = pageWidth;
    scaledHeight = scaledWidth / imageAspectRatio;
    if (scaledHeight > pageHeight) {
      scaledHeight = pageHeight;
      scaledWidth = scaledHeight * imageAspectRatio;
    }
  } else {
    scaledHeight = pageHeight;
    scaledWidth = scaledHeight * imageAspectRatio;
    if (scaledWidth > pageWidth) {
      scaledWidth = pageWidth;
      scaledHeight = scaledWidth / imageAspectRatio;
    }
  }

  pdf.addPage(
    pw.Page(
      pageFormat: pageFormat,
      margin: const pw.EdgeInsets.symmetric(vertical: 20),
      build: (pw.Context context) {
        return pw.UrlLink(
          destination: url,
          child: pw.Container(
            alignment: pw.Alignment.center,
            child: pw.Image(
              image,
              height: scaledHeight,
              fit: pw.BoxFit.fitHeight,
            ),
          ),
        );
      },
    ),
  );

  pdf.save().then((value) {
    _exportScreenshotToPdf(value, refCode: refCode, showLoading: showLoading);
  });
}