processAndSavePdf function

Future<Uint8List> processAndSavePdf({
  1. required Uint8List originalPdfBytes,
  2. required List<PageEditDto> edits,
  3. required double screenWidth,
})

Implementation

Future<Uint8List> processAndSavePdf({
  required Uint8List originalPdfBytes,
  required List<PageEditDto> edits,
  required double screenWidth,
}) async {
  final PdfDocument pdfDoc = PdfDocument(inputBytes: originalPdfBytes);

  for (final edit in edits) {
    final page = pdfDoc.pages[edit.pageIndex];
    final width = page.getClientSize().width;
    final height = page.getClientSize().height;

    final scaleX = width / screenWidth;
    final scaleY = height / (screenWidth * 1.414);

    for (final action in edit.highlight) {
      if (action.isAdd) {
        for (final ann in action.pdfAnnotation) {
          page.annotations.add(ann);
        }
      }
    }

    for (final action in edit.underline) {
      if (action.isAdd) {
        for (final ann in action.pdfAnnotation) {
          page.annotations.add(ann);
        }
      }
    }

    for (final image in edit.images) {
      final pdfImage = PdfBitmap(image.imageBytes);

      final dx = image.position.dx * scaleX;
      final dy = image.position.dy * scaleY;
      final w = image.width * scaleX;
      final h = image.height * scaleY;

      page.graphics.save();
      page.graphics.translateTransform(dx + w / 2, dy + h / 2);
      page.graphics.rotateTransform(image.rotation * (180 / pi));
      page.graphics.drawImage(
        pdfImage,
        Rect.fromLTWH(-w / 2 + 14, -h / 2 + 14, w, h),
      );
      page.graphics.restore();
    }

    if (edit.drawingBytes != null) {
      final image = PdfBitmap(edit.drawingBytes!);
      page.graphics.drawImage(image, Rect.fromLTWH(0, 0, width, height));
    }

    for (final box in edit.textBoxes) {
      final dx = box.position.dx * scaleX;
      final dy = box.position.dy * scaleY;
      final w = box.width * scaleX;
      final h = box.height * scaleY;

      final font = PdfStandardFont(PdfFontFamily.helvetica, box.fontSize);
      final brush = PdfSolidBrush(
        PdfColor(
          box.color?.red ?? 0,
          box.color?.green ?? 0,
          box.color?.blue ?? 0,
        ),
      );

      page.graphics.drawString(
        box.text,
        font,
        brush: brush,
        bounds: Rect.fromLTWH(dx + 10, dy + 10, w, h),
        format: PdfStringFormat(
          alignment: PdfTextAlignment.center,
          lineAlignment: PdfVerticalAlignment.middle,
        ),
      );
    }
  }

  final result = await pdfDoc.save();
  pdfDoc.dispose();
  return Uint8List.fromList(result);
}