raster method
Convert a Pdf document to bitmap images
Implementation
@override
Stream<PdfRaster> raster(
Uint8List document,
List<int>? pages,
double dpi,
) async* {
await _initPlugin();
final settings = Settings()..data = document.toJS;
if (!_hasPdfJsLib) {
settings
..cMapUrl = '$_pdfJsUrlBase/cmaps/'
..cMapPacked = true;
}
final jsDoc = getDocument(settings);
try {
final doc = await jsDoc.promise.toDart;
final numPages = doc.numPages;
final canvas =
web.window.document.createElement('canvas') as web.HTMLCanvasElement;
final context = canvas.getContext('2d')! as web.CanvasRenderingContext2D;
final computedPages =
pages ?? Iterable<int>.generate(numPages, (index) => index);
for (final pageIndex in computedPages) {
final page = await doc.getPage(pageIndex + 1).toDart;
try {
final viewport =
page.getViewport(Settings()..scale = dpi / PdfPageFormat.inch);
canvas.height = viewport.height.toInt();
canvas.width = viewport.width.toInt();
final renderContext = Settings()
..canvasContext = context
..viewport = viewport;
await page.render(renderContext).promise.toDart;
// Convert the image to PNG
final completer = Completer<void>();
final blobCompleter = Completer<web.Blob?>();
canvas.toBlob(
// ignore: unnecessary_lambdas
(web.Blob? blob) {
blobCompleter.complete(blob);
}.toJS,
);
final blob = await blobCompleter.future;
if (blob == null) {
continue;
}
final data = BytesBuilder();
final r = web.FileReader();
r.readAsArrayBuffer(blob);
r.onLoadEnd.listen(
(web.ProgressEvent e) {
data.add((r.result! as js.JSArrayBuffer).toDart.asInt8List());
completer.complete();
},
);
await completer.future;
yield _WebPdfRaster(
canvas.width,
canvas.height,
data.toBytes(),
);
} finally {
page.cleanup();
}
}
} finally {
jsDoc.destroy();
}
}