fillInDocument method

Future<void> fillInDocument(
  1. Document pdf,
  2. Project project,
  3. RegionFormMap map, {
  4. List<Widget> extraWidgets = const [],
})

Implementation

Future<void> fillInDocument(
    pw.Document pdf, Project project, RegionFormMap map,
    {List<pw.Widget> extraWidgets = const []}) async {
  // 1. Load Template
  // Note: In a real environment, we'd need to know if this asset is an Image or a PDF.
  // ... (comments elided for brevity if desired, but keeping logic) ...

  final templateBytes = await rootBundle.load(map.templateAsset);

  pw.MemoryImage? templateImage;
  if (map.templateAsset.toLowerCase().endsWith('.pdf')) {
    // Rasterize the first page of the PDF to an image
    try {
      await for (final page in Printing.raster(
          templateBytes.buffer.asUint8List(),
          pages: [0],
          dpi: 72)) {
        final image = await page.toPng();
        templateImage = pw.MemoryImage(image);
        break;
      }
    } catch (e) {
      // Silently fail if template rasterization fails
    }
  } else {
    templateImage = pw.MemoryImage(templateBytes.buffer.asUint8List());
  }

  // 2. Main Page with Overlay
  pdf.addPage(
    pw.Page(
      pageFormat: PdfPageFormat.a4,
      margin: pw.EdgeInsets.zero, // Full bleed
      build: (context) {
        return pw.Stack(
          children: [
            // Background
            if (templateImage != null)
              pw.Positioned.fill(
                child: pw.Image(templateImage, fit: pw.BoxFit.cover),
              ),

            // Grid for Calibration
            if (debugGrid) _buildDebugGrid(),

            // Data Fields
            _buildTextAt(map.titularPos, project.client ?? ""),
            _buildTextAt(
                map.direccionPos, "C/ Ejemplo, 123 (Sevilla)"), // Mock
            _buildTextAt(map.tensionPos, "230 V"), // Mock
            _buildTextAt(map.potenciaPos, "5.75 kW"), // Mock

            // Signature
            _buildSignature(map),

            // Overflow Note (if needed)
            if (_shouldOverflow(project, map))
              pw.Positioned(
                  left: 50,
                  top: 500, // Approx middle of table
                  child: pw.Text("VER ANEXO DE CIRCUITOS",
                      style: pw.TextStyle(
                          color: PdfColors.red,
                          fontWeight: pw.FontWeight.bold,
                          fontSize: 14))),

            // Extra Widgets (Specifics)
            ...extraWidgets,
          ],
        );
      },
    ),
  );

  // 3. Annex Page (if overflow)
  if (_shouldOverflow(project, map)) {
    _addAnnexPage(pdf, project);
  }
}