mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
PDF: fix segment closing, admission, glyph colour and PDFium reuse
- Process a closing segment's own geometry before marking the subpath closed, so a closing Bezier endpoint cannot leak control points into the next curve. - Estimate retained memory from tile-aligned page bounds (including the page's X offset) instead of raw pixels: a 1 x 10,000 px page admits its 40 tiles, not 10,000 pixels. - Sample text colour from the glyph ink (the pixel farthest from the box's dominant colour) instead of the bounds' top-left corner, which was usually background or antialiasing. - Cache the PDFium bind: pdfium-render binds once per process, so a second PDF import in one session failed with PdfiumLibraryBindingsAlreadyInitialized. - Add a PDFium-backed two-page end-to-end test with a transformed path on page 2 and non-origin red/green text at 72 and 300 dpi; it prints an explicit SKIPPED line when PDFium is unavailable. - package.ps1: pin pdfium-binaries chromium/8138, verify the archive and any cached DLL against SHA-256, drop a stale bin/pdfium.dll before extraction and check tar's exit status.
This commit is contained in:
1 parent
192b075bfa
commit
fabfbb5d5a
4 files changed
+291
-30
No files matched your search
+110
-27
@@ -82,11 +82,21 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) -
|
||||
// The aggregate budget: the document keeps every page's raster tiles, while one page at a
|
||||
// time is converted through the PDFium bitmap, its RGBA copy and the f32 buffer.
|
||||
let page_px = |w: f64, h: f64| (w * dpi / 72.0).round().max(1.0) * (h * dpi / 72.0).round().max(1.0);
|
||||
let page_pixels = sizes.iter().map(|&(w, h)| page_px(w, h)).sum::<f64>();
|
||||
let max_page_pixels = sizes.iter().map(|&(w, h)| page_px(w, h)).fold(0.0_f64, f64::max);
|
||||
// 4 bytes/px of retained RGBA tiles for every page, plus 24 bytes/px (bitmap, RGBA copy,
|
||||
// f32 conversion buffer) for the page being converted.
|
||||
let estimate = (page_pixels * 4.0 + max_page_pixels * 24.0) as u64;
|
||||
// Retained backing: a page occupies whole 256 px tiles, including the ones its document X
|
||||
// offset steps into. A 1 x 10,000 px page is 40 tiles (10 MiB), not 10,000 pixels.
|
||||
const TILE: u64 = 256;
|
||||
let mut retained: u64 = 0;
|
||||
let mut page_x: u64 = 0;
|
||||
for &(w, h) in &sizes {
|
||||
let px = (w * dpi / 72.0).round().max(1.0) as u64;
|
||||
let py = (h * dpi / 72.0).round().max(1.0) as u64;
|
||||
let tiles_x = (page_x + px).div_ceil(TILE) - page_x / TILE;
|
||||
retained = retained.saturating_add(tiles_x.saturating_mul(py.div_ceil(TILE)).saturating_mul(TILE * TILE * 4));
|
||||
page_x += px + u64::from(GAP);
|
||||
}
|
||||
// Plus 24 bytes/px (bitmap, RGBA copy, f32 conversion buffer) for the page being converted.
|
||||
let estimate = retained.saturating_add((max_page_pixels * 24.0) as u64);
|
||||
let budget = if opts.flat_max_pixel_bytes > 0 { opts.flat_max_pixel_bytes } else { DEFAULT_MAX_PIXEL_BYTES };
|
||||
if estimate > budget {
|
||||
return Err(IoError::Unsupported(format!(
|
||||
@@ -189,6 +199,56 @@ impl PageFrame<'_> {
|
||||
Color::BLACK
|
||||
}
|
||||
}
|
||||
|
||||
/// The ink colour of the text in `bounds` (page points).
|
||||
///
|
||||
/// The box holds both glyphs and the page behind them, so sampling one corner usually finds
|
||||
/// background or an antialiased edge. Take the pixel farthest from the box's most common
|
||||
/// colour instead: for dark text on a light page that is a glyph core, and for light text on a
|
||||
/// dark page it is the glyph rather than the background.
|
||||
fn text_color(&self, left: f32, top: f32, right: f32, bottom: f32) -> Color {
|
||||
let x0 = (f64::from(left) * self.dpi / 72.0).floor().max(0.0) as u32;
|
||||
let x1 = (f64::from(right) * self.dpi / 72.0).ceil().clamp(0.0, f64::from(self.width)) as u32;
|
||||
// PDF's Y grows up; the rendered page's Y grows down.
|
||||
let y0 = ((self.height_pt - f64::from(top)) * self.dpi / 72.0).floor().max(0.0) as u32;
|
||||
let y1 = ((self.height_pt - f64::from(bottom)) * self.dpi / 72.0).ceil().clamp(0.0, f64::from(self.height)) as u32;
|
||||
if x1 <= x0 || y1 <= y0 {
|
||||
return Color::BLACK;
|
||||
}
|
||||
// At most ~4096 samples, so a page-sized text box stays cheap.
|
||||
let step = ((f64::from(x1 - x0) * f64::from(y1 - y0) / 4096.0).sqrt().ceil() as u32).max(1);
|
||||
let mut samples: Vec<[f32; 3]> = Vec::new();
|
||||
let mut buckets: std::collections::HashMap<u32, (u32, [f32; 3])> = std::collections::HashMap::new();
|
||||
let mut y = y0;
|
||||
while y < y1 {
|
||||
let mut x = x0;
|
||||
while x < x1 {
|
||||
let c = self.color_at(x, y);
|
||||
let rgb = [c.c[0], c.c[1], c.c[2]];
|
||||
let key = (rgb[0] * 31.0) as u32 * 1024 + (rgb[1] * 31.0) as u32 * 32 + (rgb[2] * 31.0) as u32;
|
||||
let entry = buckets.entry(key).or_insert((0, [0.0; 3]));
|
||||
entry.0 += 1;
|
||||
for (sum, v) in entry.1.iter_mut().zip(rgb) {
|
||||
*sum += v;
|
||||
}
|
||||
samples.push(rgb);
|
||||
x += step;
|
||||
}
|
||||
y += step;
|
||||
}
|
||||
let Some((_, (count, sum))) = buckets.iter().max_by_key(|(_, (count, _))| *count) else { return Color::BLACK };
|
||||
let mode = [sum[0] / *count as f32, sum[1] / *count as f32, sum[2] / *count as f32];
|
||||
let mut best = mode;
|
||||
let mut best_distance = -1.0f32;
|
||||
for rgb in samples {
|
||||
let distance = (rgb[0] - mode[0]).powi(2) + (rgb[1] - mode[1]).powi(2) + (rgb[2] - mode[2]).powi(2);
|
||||
if distance > best_distance {
|
||||
best_distance = distance;
|
||||
best = rgb;
|
||||
}
|
||||
}
|
||||
Color::rgb(best[0], best[1], best[2])
|
||||
}
|
||||
}
|
||||
|
||||
/// Editable text and shape layers for one rendered page, in document pixels.
|
||||
@@ -196,7 +256,6 @@ impl PageFrame<'_> {
|
||||
fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, frame: &PageFrame) -> Vec<Layer> {
|
||||
use pdfium_render::prelude::*;
|
||||
|
||||
let PageFrame { x, width: page_width, height: page_height, .. } = *frame;
|
||||
let objects = page.objects();
|
||||
let mut layers = Vec::new();
|
||||
for object in objects.iter() {
|
||||
@@ -208,12 +267,9 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f
|
||||
}
|
||||
let Ok(bounds) = text.bounds() else { continue };
|
||||
let (x_px, y_px) = frame.to_doc(bounds.left().value, bounds.top().value);
|
||||
// The text layer's size is in points; the transform is in document pixels.
|
||||
// The text object does not expose its fill colour; sample the rendered page at the
|
||||
// text's top-left corner so the editable layer starts with the right colour.
|
||||
let cx = ((x_px - f64::from(x)).max(0.0) as u32).min(page_width.saturating_sub(1));
|
||||
let cy = (y_px.max(0.0) as u32).min(page_height.saturating_sub(1));
|
||||
let color = frame.color_at(cx, cy);
|
||||
// The text layer's size is in points; the transform is in document pixels. The
|
||||
// text object does not expose its fill colour; sample the glyph ink from the page.
|
||||
let color = frame.text_color(bounds.left().value, bounds.top().value, bounds.right().value, bounds.bottom().value);
|
||||
let size_pt = f64::from(text.scaled_font_size().value).max(1.0);
|
||||
let font = text.font();
|
||||
let family = if font.family().is_empty() { font.name() } else { font.family() };
|
||||
@@ -249,10 +305,6 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f
|
||||
let mut bezier: Vec<(f64, f64)> = Vec::new();
|
||||
for segment in path.segments().transform(matrix).iter() {
|
||||
let point = || frame.to_doc(segment.x().value, segment.y().value);
|
||||
if segment.is_close() {
|
||||
closed = true;
|
||||
continue;
|
||||
}
|
||||
match segment.segment_type() {
|
||||
PdfPathSegmentType::MoveTo => {
|
||||
if !knots.is_empty() {
|
||||
@@ -281,6 +333,11 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f
|
||||
}
|
||||
PdfPathSegmentType::Unknown => {}
|
||||
}
|
||||
// A closing segment can also be the endpoint that closes a Bézier; process it
|
||||
// above before marking the subpath closed so its control points are consumed.
|
||||
if segment.is_close() {
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
if !knots.is_empty() {
|
||||
subpaths.push(Subpath { closed, knots, op: PathOp::Combine });
|
||||
@@ -325,22 +382,35 @@ fn effective_dpi(requested: f64, sizes: &[(f64, f64)], gap: u32, max_page: f64,
|
||||
}
|
||||
|
||||
/// Loads the PDFium shared library from the executable's folder (`PDFIUM_DIR` overrides it).
|
||||
///
|
||||
/// pdfium-render keeps the bindings in a process-wide static: the first import initializes them
|
||||
/// and later `bind_to_library` calls fail with `PdfiumLibraryBindingsAlreadyInitialized`. Remember
|
||||
/// the outcome and reuse the initialized bindings, so opening a second PDF in one session works.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn bind() -> Result<pdfium_render::prelude::Pdfium, IoError> {
|
||||
use pdfium_render::prelude::Pdfium;
|
||||
|
||||
let dir = std::env::var_os("PDFIUM_DIR")
|
||||
.map(std::path::PathBuf::from)
|
||||
.unwrap_or_else(|| std::env::current_exe().ok().and_then(|exe| exe.parent().map(std::path::Path::to_path_buf)).unwrap_or_default());
|
||||
let library = Pdfium::pdfium_platform_library_name_at_path(&dir);
|
||||
let platform = Pdfium::pdfium_platform_library_name().to_string_lossy().into_owned();
|
||||
let bindings = Pdfium::bind_to_library(&library).map_err(|e| {
|
||||
IoError::Unsupported(format!(
|
||||
"PDF import: cannot load PDFium from {} ({e}); put {platform} next to the executable or set PDFIUM_DIR",
|
||||
library.display()
|
||||
))
|
||||
})?;
|
||||
Ok(Pdfium::new(bindings))
|
||||
static INIT: std::sync::OnceLock<Result<(), String>> = std::sync::OnceLock::new();
|
||||
let init = INIT.get_or_init(|| {
|
||||
let dir = std::env::var_os("PDFIUM_DIR")
|
||||
.map(std::path::PathBuf::from)
|
||||
.unwrap_or_else(|| std::env::current_exe().ok().and_then(|exe| exe.parent().map(std::path::Path::to_path_buf)).unwrap_or_default());
|
||||
let library = Pdfium::pdfium_platform_library_name_at_path(&dir);
|
||||
let platform = Pdfium::pdfium_platform_library_name().to_string_lossy().into_owned();
|
||||
match Pdfium::bind_to_library(&library) {
|
||||
Ok(bindings) => {
|
||||
// Initializes the library inside pdfium-render's process-wide bindings.
|
||||
drop(Pdfium::new(bindings));
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => Err(format!("PDF import: cannot load PDFium from {} ({e}); put {platform} next to the executable or set PDFIUM_DIR", library.display())),
|
||||
}
|
||||
});
|
||||
match init {
|
||||
// The bindings are already initialized; `default()` re-uses them.
|
||||
Ok(()) => Ok(Pdfium::default()),
|
||||
Err(message) => Err(IoError::Unsupported(message.clone())),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -369,4 +439,17 @@ mod tests {
|
||||
assert_eq!(page.color_at(1, 0), photocraft_doc::Color::BLACK);
|
||||
assert_eq!(page.color_at(2, 0), photocraft_doc::Color::BLACK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_colour_samples_the_glyph_ink() {
|
||||
// An 8 x 4 white page with one black glyph pixel at (2, 1).
|
||||
let mut rgba = vec![255u8; 8 * 4 * 4];
|
||||
let glyph = (8 + 2) * 4;
|
||||
rgba[glyph..glyph + 3].fill(0);
|
||||
let page = PageFrame { height_pt: 4.0, dpi: 72.0, x: 0, rgba: &rgba, width: 8, height: 4 };
|
||||
// The whole page box contains the glyph: the ink wins over the white background.
|
||||
assert_eq!(page.text_color(0.0, 4.0, 8.0, 0.0), photocraft_doc::Color::BLACK);
|
||||
// A box that contains only background keeps the background colour.
|
||||
assert_eq!(page.text_color(4.0, 4.0, 8.0, 2.0), photocraft_doc::Color::rgb(1.0, 1.0, 1.0));
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,7 @@ mod orientation;
|
||||
mod pattern_fill_psd;
|
||||
mod pcraft_full_composite;
|
||||
mod pcraft_manifest_name;
|
||||
mod pdf_import;
|
||||
mod pdn_corpus;
|
||||
mod png_steps;
|
||||
mod png_text_metadata;
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
//! PDF import end-to-end through PDFium.
|
||||
//!
|
||||
//! A synthetic two-page PDF with non-origin red text, a transformed blue rectangle and green text
|
||||
//! is imported at 72 and 300 DPI, and the resulting editable layers are checked against the
|
||||
//! fixture's geometry and pixels. PDFium is loaded at run time: when it is unavailable (no
|
||||
//! `PDFIUM_DIR`, no DLL beside the test binary) the test prints an explicit SKIPPED line and
|
||||
//! returns instead of pretending the end-to-end wiring passed.
|
||||
|
||||
use lopdf::{Document as PdfDocument, Object, Stream, dictionary};
|
||||
use photocraft_doc::{Color, Document, Layer, LayerContent, ShapeLayer, TextLayer};
|
||||
use photocraft_io::{ImportOptions, IoError, import_with_options_and_interrupt};
|
||||
|
||||
const PAGE_W: f64 = 200.0;
|
||||
const PAGE_H: f64 = 100.0;
|
||||
const GAP: f64 = 80.0;
|
||||
|
||||
#[test]
|
||||
fn imports_text_and_a_transformed_path_on_two_pages() {
|
||||
let pdf = two_page_pdf();
|
||||
for dpi in [72.0f32, 300.0] {
|
||||
let options = ImportOptions { pdf_dpi: dpi, ..Default::default() };
|
||||
let result = match import_with_options_and_interrupt("fixture.pdf", &pdf, &options, &photocraft_raster::Interrupt::NONE) {
|
||||
Ok(result) => result,
|
||||
Err(IoError::Unsupported(message)) if message.contains("cannot load PDFium") => {
|
||||
eprintln!("SKIPPED the PDF import end-to-end test: PDFium is unavailable ({message})");
|
||||
return;
|
||||
}
|
||||
Err(error) => panic!("PDF import failed at {dpi} dpi: {error}"),
|
||||
};
|
||||
check(&result.document, dpi);
|
||||
}
|
||||
}
|
||||
|
||||
/// Page 1: red 48 pt text at (20, 50). Page 2: a 20 x 10 pt rectangle scaled 2x and moved by
|
||||
/// (10, 5) — corners (30, 25)..(70, 45) — plus green 48 pt text at (20, 20).
|
||||
fn two_page_pdf() -> Vec<u8> {
|
||||
let mut pdf = PdfDocument::with_version("1.5");
|
||||
let pages_id = pdf.new_object_id();
|
||||
let font_id = pdf.add_object(dictionary! {
|
||||
"Type" => "Font",
|
||||
"Subtype" => "Type1",
|
||||
"BaseFont" => "Helvetica",
|
||||
});
|
||||
let resources = pdf.add_object(dictionary! {
|
||||
"Font" => dictionary! { "F1" => font_id },
|
||||
});
|
||||
let contents = ["1 0 0 rg BT /F1 48 Tf 20 50 Td (Red) Tj ET", "0 0 1 rg q 2 0 0 2 10 5 cm 10 10 20 10 re f Q 0 1 0 rg BT /F1 48 Tf 20 20 Td (Green) Tj ET"];
|
||||
let mut kids = Vec::new();
|
||||
for content in contents {
|
||||
let content_id = pdf.add_object(Stream::new(dictionary! {}, content.as_bytes().to_vec()));
|
||||
let page_id = pdf.add_object(dictionary! {
|
||||
"Type" => "Page",
|
||||
"Parent" => pages_id,
|
||||
"MediaBox" => Object::Array(vec![0.into(), 0.into(), Object::Real(PAGE_W as f32), Object::Real(PAGE_H as f32)]),
|
||||
"Contents" => content_id,
|
||||
"Resources" => resources,
|
||||
});
|
||||
kids.push(Object::Reference(page_id));
|
||||
}
|
||||
let count = kids.len() as i64;
|
||||
pdf.objects.insert(
|
||||
pages_id,
|
||||
Object::Dictionary(dictionary! {
|
||||
"Type" => "Pages",
|
||||
"Kids" => Object::Array(kids),
|
||||
"Count" => count,
|
||||
}),
|
||||
);
|
||||
let catalog = pdf.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id });
|
||||
pdf.trailer.set("Root", catalog);
|
||||
let mut bytes = Vec::new();
|
||||
pdf.save_to(&mut bytes).expect("writing the PDF fixture");
|
||||
bytes
|
||||
}
|
||||
|
||||
fn check(document: &Document, dpi: f32) {
|
||||
let scale = f64::from(dpi) / 72.0;
|
||||
let page_two_x = (PAGE_W * scale).round() + GAP;
|
||||
|
||||
// Page 1: the editable text keeps its position and takes the red ink from the page.
|
||||
let text = text_layer(page_children(document, 1));
|
||||
assert_red(&text.color, "page 1 text");
|
||||
let x = text.transform.m[4];
|
||||
let y = text.transform.m[5];
|
||||
assert!((x - 20.0 * scale).abs() < 8.0 * scale, "page 1 text x is {x} at {dpi} dpi");
|
||||
// 48 pt Helvetica's bounds top is about 35 pt above the baseline at y = 50.
|
||||
assert!((y - 15.0 * scale).abs() < 20.0 * scale, "page 1 text y is {y} at {dpi} dpi");
|
||||
|
||||
// Page 2: the transformed rectangle lands at (30, 25)..(70, 45) plus the page's document X.
|
||||
let shape = shape_layer(page_children(document, 2));
|
||||
let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
|
||||
for knot in shape.path.subpaths.iter().flat_map(|subpath| &subpath.knots) {
|
||||
min_x = min_x.min(knot.anchor.x);
|
||||
max_x = max_x.max(knot.anchor.x);
|
||||
min_y = min_y.min(knot.anchor.y);
|
||||
max_y = max_y.max(knot.anchor.y);
|
||||
}
|
||||
assert!((min_x - (page_two_x + 30.0 * scale)).abs() < 4.0, "path min x is {min_x}, page 2 starts at {page_two_x} ({dpi} dpi)");
|
||||
assert!((max_x - (page_two_x + 70.0 * scale)).abs() < 4.0, "path max x is {max_x} ({dpi} dpi)");
|
||||
assert!((min_y - (PAGE_H - 45.0) * scale).abs() < 4.0, "path min y is {min_y} ({dpi} dpi)");
|
||||
assert!((max_y - (PAGE_H - 25.0) * scale).abs() < 4.0, "path max y is {max_y} ({dpi} dpi)");
|
||||
|
||||
let text = text_layer(page_children(document, 2));
|
||||
assert_green(&text.color, "page 2 text");
|
||||
assert!(text.transform.m[4] > page_two_x + 10.0 * scale, "page 2 text x misses the page offset: {} <= {page_two_x}", text.transform.m[4]);
|
||||
}
|
||||
|
||||
fn page_children(document: &Document, page: usize) -> &[Layer] {
|
||||
let name = format!("Page {page}");
|
||||
let layer = document.layers.iter().find(|layer| layer.name == name).unwrap_or_else(|| panic!("no {name} layer"));
|
||||
match &layer.content {
|
||||
LayerContent::Group(group) => &group.children,
|
||||
_ => panic!("{name} is not a group"),
|
||||
}
|
||||
}
|
||||
|
||||
fn text_layer(children: &[Layer]) -> &TextLayer {
|
||||
children
|
||||
.iter()
|
||||
.find_map(|layer| match &layer.content {
|
||||
LayerContent::Text(text) => Some(text),
|
||||
_ => None,
|
||||
})
|
||||
.expect("a text layer")
|
||||
}
|
||||
|
||||
fn shape_layer(children: &[Layer]) -> &ShapeLayer {
|
||||
children
|
||||
.iter()
|
||||
.find_map(|layer| match &layer.content {
|
||||
LayerContent::Shape(shape) => Some(shape),
|
||||
_ => None,
|
||||
})
|
||||
.expect("a shape layer")
|
||||
}
|
||||
|
||||
fn assert_red(color: &Color, what: &str) {
|
||||
assert!(color.c[0] > 0.8 && color.c[1] < 0.2 && color.c[2] < 0.2, "{what} should be red, got {:?}", color.c);
|
||||
}
|
||||
|
||||
fn assert_green(color: &Color, what: &str) {
|
||||
assert!(color.c[1] > 0.8 && color.c[0] < 0.2 && color.c[2] < 0.2, "{what} should be green, got {:?}", color.c);
|
||||
}
|
||||
@@ -57,17 +57,51 @@ if (-not $env:PHOTOCRAFT_BUILD_DATE) { $env:PHOTOCRAFT_BUILD_DATE = (Get-Date).T
|
||||
|
||||
# PDF import loads PDFium at runtime. Stage the Windows build's DLL before cargo, so the app's
|
||||
# build script copies it beside the exe and both the MSI and the portable ZIP ship it.
|
||||
#
|
||||
# Pinned to a reviewed pdfium-binaries release: the archive is verified before extraction and a
|
||||
# cached DLL is verified before reuse, so a moved or compromised "latest" cannot be packaged.
|
||||
# Bump the release and both hashes together after re-checking the published build.
|
||||
$PdfiumRelease = 'chromium/8138'
|
||||
$PdfiumArchiveSha256 = @{
|
||||
x64 = '8d48973e3eb472dda0f5f2435e595ac043f9f2219dd71883392f549445afa8a5'
|
||||
x86 = '5c32d44711a73ed8ae86b85322078da8444fc696b9326527eed2d9fcd620fc84'
|
||||
arm64 = '5e04abdb36ba9b4b5c8630123eaf042036f8a62abda6e5529708fee3d35fbf4f'
|
||||
}
|
||||
$PdfiumDllSha256 = @{
|
||||
x64 = '71a3e63e6ab8f5746a0fc9de9bc3d0c0dc07eb60990dfd37d9db7fc891821943'
|
||||
x86 = 'ee592bd01eaef454aada95ed483ceca1c4f6ce0f0b9568608f40c3861fbda035'
|
||||
arm64 = '0b1b9a52b3297448cbe461ffbca1455603d85161d5e96090e1a89bd7c4a62a33'
|
||||
}
|
||||
$PdfiumDir = Join-Path $Root "target\pdfium\$Arch"
|
||||
$PdfiumDll = Join-Path $PdfiumDir 'pdfium.dll'
|
||||
|
||||
function Get-Sha256([string] $Path) { (Get-FileHash -Algorithm SHA256 -LiteralPath $Path).Hash.ToLowerInvariant() }
|
||||
|
||||
if (Test-Path -LiteralPath $PdfiumDll) {
|
||||
$actualDll = Get-Sha256 $PdfiumDll
|
||||
if ($actualDll -ne $PdfiumDllSha256[$Arch]) {
|
||||
Write-Warning "cached PDFium DLL is not the pinned $PdfiumRelease build ($actualDll); re-downloading"
|
||||
Remove-Item -LiteralPath $PdfiumDll -Force
|
||||
}
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $PdfiumDll)) {
|
||||
$expectedArchive = $PdfiumArchiveSha256[$Arch]
|
||||
if (-not $expectedArchive) { throw "no pinned PDFium checksum for $Arch" }
|
||||
$tgz = Join-Path $env:TEMP "pdfium-win-$Arch.tgz"
|
||||
Invoke-Native "download PDFium ($Arch)" {
|
||||
Invoke-WebRequest -Uri "https://github.com/bblanchon/pdfium-binaries/releases/latest/download/pdfium-win-$Arch.tgz" -OutFile $tgz
|
||||
Invoke-Native "download PDFium ($Arch, $PdfiumRelease)" {
|
||||
Remove-Item -LiteralPath $tgz -Force -ErrorAction SilentlyContinue
|
||||
Invoke-WebRequest -Uri "https://github.com/bblanchon/pdfium-binaries/releases/download/$PdfiumRelease/pdfium-win-$Arch.tgz" -OutFile $tgz
|
||||
$actualArchive = Get-Sha256 $tgz
|
||||
if ($actualArchive -ne $expectedArchive) { throw "PDFium $Arch archive checksum $actualArchive does not match the pinned $expectedArchive" }
|
||||
New-Item -ItemType Directory -Force -Path $PdfiumDir | Out-Null
|
||||
tar -xzf $tgz -C $PdfiumDir
|
||||
# A DLL left in bin\ by an earlier run must not be mistaken for this archive's extraction.
|
||||
$extracted = Join-Path $PdfiumDir 'bin\pdfium.dll'
|
||||
Remove-Item -LiteralPath $extracted -Force -ErrorAction SilentlyContinue
|
||||
tar -xzf $tgz -C $PdfiumDir
|
||||
if ($LASTEXITCODE -ne 0) { throw "PDFium $Arch archive extraction failed with exit code $LASTEXITCODE" }
|
||||
if (-not (Test-Path -LiteralPath $extracted)) { throw 'PDFium archive had no bin/pdfium.dll' }
|
||||
Move-Item -Force $extracted $PdfiumDll
|
||||
Remove-Item -LiteralPath $tgz -Force
|
||||
}
|
||||
}
|
||||
$env:PDFIUM_DLL = $PdfiumDll
|
||||
|
||||
Reference in new issue
Block a user