Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PDF splitting with Syncfusion truncates pages #2243

Open
aliboy007 opened this issue Jan 7, 2025 · 1 comment
Open

PDF splitting with Syncfusion truncates pages #2243

aliboy007 opened this issue Jan 7, 2025 · 1 comment
Labels
open Open pdf PDF component

Comments

@aliboy007
Copy link

Bug description

When splitting a PDF into individual pages using the Syncfusion PDF library in Flutter, the output pages are truncated or incomplete. This issue occurs regardless of the PDF size or complexity and affects the integrity of the resulting pages.

Steps to reproduce

Set up a Flutter project and include the Syncfusion PDF library (syncfusion_flutter_pdf).

Implement a workflow to split a multi-page PDF into individual pages using the createTemplate method.

Use the following code to load a PDF, split it into individual pages, and save them:

Load the resulting split pages using a PDF viewer (e.g., Syncfusion PDF Viewer or similar tools).

Code sample

Code sample
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_pdf/pdf.dart';
import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart';
import 'package:file_picker/file_picker.dart';
import 'package:path_provider/path_provider.dart';

class PdfSamplePage extends StatefulWidget {
  const PdfSamplePage({Key? key}) : super(key: key);

  @override
  State<PdfSamplePage> createState() => _PdfSamplePageState();
}

class _PdfSamplePageState extends State<PdfSamplePage> {
  List<String> _splitPagePaths = [];

  Future<void> _pickAndSplitPdf() async {
    try {
      FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['pdf'], // Restrict to PDF files
      );

      if (result != null && result.files.single.path != null) {
        File pdfFile = File(result.files.single.path!);

        // Split the PDF into pages
        List<File> splitFiles = await _splitPdfIntoPages(pdfFile);

        setState(() {
          _splitPagePaths = splitFiles.map((file) => file.path).toList();
        });
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('No file selected')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Error picking or splitting file: $e')),
      );
    }
  }

  Future<List<File>> _splitPdfIntoPages(File pdfFile) async {
    final pdfBytes = await pdfFile.readAsBytes();
    final document = PdfDocument(inputBytes: pdfBytes);

    List<File> pageFiles = [];
    final appDir = await getApplicationDocumentsDirectory();

    for (int i = 0; i < document.pages.count; i++) {
      final page = PdfDocument();
      page.pages.add().graphics.drawPdfTemplate(
            document.pages[i].createTemplate(),
            Offset(0, 0),
          );

      final pageBytes = page.saveSync();
      final pageFile = File('${appDir.path}/page_${i + 1}.pdf');
      await pageFile.writeAsBytes(pageBytes);

      pageFiles.add(pageFile);
      page.dispose();
    }

    document.dispose();
    return pageFiles;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('PDF Split and Viewer'),
      ),
      body: Column(
        children: [
          ElevatedButton(
            onPressed: _pickAndSplitPdf,
            child: const Text('Pick and Split PDF File'),
          ),
          const SizedBox(height: 10),
          Expanded(
            child: _splitPagePaths.isNotEmpty
                ? ListView.builder(
                    itemCount: _splitPagePaths.length,
                    itemBuilder: (context, index) {
                      return Padding(
                        padding: const EdgeInsets.symmetric(vertical: 8.0),
                        child: SizedBox(
                          height: 400, // Fixed height for each page preview
                          child: SfPdfViewer.file(
                            File(_splitPagePaths[index]),
                            pageSpacing: 0,
                            enableDoubleTapZooming: false,
                            enableTextSelection: false,
                            pageLayoutMode: PdfPageLayoutMode.single,
                            canShowPaginationDialog: false,
                            canShowScrollHead: false,
                            canShowScrollStatus: false,
                            initialZoomLevel: 1.0,
                          ),
                        ),
                      );
                    },
                  )
                : const Center(
                    child: Text('No PDF selected or split yet.'),
                  ),
          ),
        ],
      ),
    );
  }
}

Screenshots or Video

Screenshots / Video demonstration

IMG_1DD3235A8078-1
IMG_2AF54BAD44EA-1
IMG_71E42D8B2D70-1
IMG_A07DBDEC5EA4-1

The margin ones are split PDFs and without margin are original pages.

Stack Traces

No specific stack trace, but the issue is evident in the truncated output files.

On which target platforms have you observed this bug?

Android, iOS

Flutter Doctor output

Doctor output
[✓] Flutter (Channel stable, 3.27.0, on macOS 15.2 24C101 darwin-arm64, locale en-AU)
    • Flutter version 3.27.0 on channel stable at /Users/<username>/Developer/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 8495dee1fd (4 weeks ago), 2024-12-10 14:23:39 -0800
    • Engine revision 83bacfc525
    • Dart version 3.6.0
    • DevTools version 2.40.2

[✓] Android toolchain - develop for Android devices (Android SDK version 35.0.0)
    • Android SDK at /Users/<username>/Library/Android/sdk
    • Platform android-35, build-tools 35.0.0
    • ANDROID_HOME = /Users/<username>/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 21.0.3+-79915917-b509.11)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 16.2)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 16C5032a
    • CocoaPods version 1.16.2

[✓] Android Studio (version 2024.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 21.0.3+-79915917-b509.11)

[✓] VS Code (version 1.92.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.102.0

[✓] Connected device (2 available)
    • iPhone (mobile)                 • <device-id>               • ios    • iOS 17.7.1
    • Mac Designed for iPad (desktop) • mac-designed-for-ipad     • darwin • macOS 15.2

[✓] Network resources
    • All expected network resources are available.

• No issues found!
@aliboy007
Copy link
Author

I found the issue - it is to with the margins.

`Future<List> _splitPdfIntoPages(File pdfFile) async {
final pdfBytes = await pdfFile.readAsBytes();
final document = PdfDocument(inputBytes: pdfBytes);

List pageFiles = [];
final appDir = await getApplicationDocumentsDirectory();

for (int i = 0; i < document.pages.count; i++) {
final originalPage = document.pages[i];
final originalSize = originalPage.size; // Get original page size (width, height)

final newDocument = PdfDocument();

// Explicitly set margins to zero
newDocument.pageSettings.margins.all = 0;

final newPage = newDocument.pages.add();
final graphics = newPage.graphics;

// Draw the content of the original page to the new page
graphics.drawPdfTemplate(
  originalPage.createTemplate(),
  Offset.zero, // No offset
);

// Save the new page as a file
final pageBytes = newDocument.saveSync();
final pageFile = File('${appDir.path}/page_${i + 1}.pdf');
await pageFile.writeAsBytes(pageBytes);

pageFiles.add(pageFile);
newDocument.dispose();

}

document.dispose();
return pageFiles;
}
`

@LavanyaGowtham2021 LavanyaGowtham2021 added pdf PDF component open Open labels Jan 7, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
open Open pdf PDF component
Projects
None yet
Development

No branches or pull requests

2 participants