Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

PDF toolkit: review fixes (stamps on turned and cropped pages, password)

cre8ive-marketingdcebddcbace6
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 5cd601a2..1f21a4af 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -48,6 +48,8 @@
Each name stays reserved while a conversion holds it. A conversion that fails or is cancelled deletes what it began
writing, but only at a path that was its alone: nothing was there before and no other conversion was handed the
same name ("Overwrite"). It frees its names and removes an output folder it made if that is left empty.
+ A PDF target's finishing (watermark, page numbers, password; `IPdfFinisher`) runs after the last step, on every
+ PDF a file became, and once on a merged PDF.
"Merge into one PDF" converts each file to PDF and merges with PDFsharp.
"Compress into one archive" packs the dropped files, unconverted, with the archive engine (`IFileCombiner`).
"Merge videos", "Merge audio" and "Video from images" join the files, in the order picked in the merge order
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 2adaa1c0..0f7aa6b7 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -735,11 +735,16 @@ wrote it (PDFsharp, rhwp, LibreOffice, Ghostscript …), and once on a merged PD
- **Watermark**: the text in light grey (22 % opacity), bold, along the page's diagonal over the content, at 70 % of
the diagonal and at most a quarter of the short side high.
- **Page numbers**: "3 / 10", 9 pt dark grey, centred 10 mm above the bottom edge.
+- Both go on the page as it is shown: centred in its crop box (the media box when it has none), the right way up
+ for its `/Rotate`. The page is drawn on unturned and its `/Rotate` put back.
- Text is drawn as glyph outlines (`Vector/GlyphOutlines.cs`, HarfBuzz shaping, shared with SVG text in PDFs). Any
script works with a font the PC has for it (Skia's font fallback, else Arial or the default face), and no font is
embedded, so the PDF grows by a few kilobytes. The text can't be selected or searched.
- **Password**: opens the PDF (user and owner password are the same), AES-256 (`SetEncryptionToV5`). It is saved with
- the preset in the settings file. A password makes a PDF/A no longer conform, since PDF/A forbids encryption.
+ the preset in the settings file, but left out of a preset export and of the copy history keeps to convert failed
+ files again: a retry takes it from the preset again, and fails (`error.pdf_password_gone`) when the preset no
+ longer has one. The editor takes at most 127 UTF-8 bytes, all that AES-256 readers use, and turns the box off while
+ PDF/A is ticked, since PDF/A forbids encryption.
## Office Open XML variants
diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.json
index ffd9cce5..172fd57b 100644
--- a/src/Filee.App/Assets/i18n/ar.json
+++ b/src/Filee.App/Assets/i18n/ar.json
@@ -90,6 +90,7 @@
"error.needs_shaping": "يحتاج هذا النص إلى LibreOffice لتحويله بصورة صحيحة. ثبّته من الإعدادات ← المحركات",
"error.runtime_missing": "أحد ملفات وقت تشغيل Microsoft Visual C++ التي يحتاجها هذا المحرك مفقود أو قديم. حدّث Filee أو أعد تثبيته، أو ثبّت Microsoft Visual C++ Redistributable ‏(x64)",
"error.conversion_failed": "أبلغ المحرك عن خطأ",
+ "error.pdf_password_gone": "لا تُحفظ كلمة مرور PDF الخاصة بالإعداد المسبق في السجل، ولم يعد الإعداد المسبق يحملها. حوّل الملفات مرة أخرى بإعداد مسبق يحمل كلمة المرور.",
"error.web_download_failed": "تعذّر تنزيل الملف",
"error.web_page": "يفتح الرابط صفحة ويب وليس ملفًا. لا يستطيع Filee تنزيل ملف يتطلب تسجيل الدخول: احفظه من المتصفح أولًا",
"error.web_too_large": "حجم الملف أكبر من 2 غيغابايت",
@@ -530,7 +531,7 @@
"presets.watermark": "علامة مائية",
"presets.watermark_hint": "مثلًا: مسودة",
"presets.pdf_password": "كلمة مرور الفتح",
- "presets.pdf_password_hint": "اتركه فارغًا بلا كلمة مرور. تُحفظ مع الإعداد المسبق، فاستخدم كلمة مرور لهذا النوع من الملفات فقط.",
+ "presets.pdf_password_hint": "اتركه فارغًا بلا كلمة مرور. تُحفظ مع الإعداد المسبق، فاستخدم كلمة مرور لهذا النوع من الملفات فقط. لا يمكن أن يحمل ملف PDF/A كلمة مرور، لذا يتعطل هذا الحقل عند تحديد PDF/A.",
"presets.page_numbers": "أرقام الصفحات (1 / 5 في الأسفل)",
"presets.combine_pages_hint": "يضع كل الصفحات تحت بعضها في صورة واحدة.\nتُصغّر النتائج الطويلة جدًا إلى حد الصيغة (JPG ‏65,500 بكسل، WebP ‏16,383 بكسل).",
"presets.combine_pages": "تجميع الصفحات في صورة طويلة واحدة (عند تحويل PDF)",
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 93917ae1..6613d78a 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -96,6 +96,7 @@
"error.needs_shaping": "This script needs LibreOffice to convert correctly. Install it in Settings → Engines",
"error.runtime_missing": "A Microsoft Visual C++ runtime file this engine needs is missing or outdated. Update or reinstall Filee, or install the Microsoft Visual C++ Redistributable (x64)",
"error.conversion_failed": "The engine reported an error",
+ "error.pdf_password_gone": "The preset's PDF password isn't kept in the history, and the preset no longer has one. Convert the files again with a preset that has the password.",
"error.web_download_failed": "Couldn't download the file",
"error.web_page": "The link opens a web page, not a file. Filee can't download a file that needs you to sign in: save it from the browser first",
"error.web_too_large": "The file is larger than 2 GB",
@@ -545,7 +546,7 @@
"presets.watermark": "Watermark",
"presets.watermark_hint": "e.g. DRAFT",
"presets.pdf_password": "Password to open",
- "presets.pdf_password_hint": "Empty for none. It is saved with the preset, so use one only for this kind of file.",
+ "presets.pdf_password_hint": "Empty for none. It is saved with the preset, so use one only for this kind of file. PDF/A can't have a password, so it's off while PDF/A is ticked.",
"presets.page_numbers": "Page numbers (1 / 5 at the bottom)",
"presets.combine_pages_hint": "Puts all pages one under another in a single image.\nVery long results are scaled to the format's limit (JPG 65,500 px, WebP 16,383 px).",
"presets.combine_pages": "Stack the pages into one tall image (when a PDF is converted)",
diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json
index 50f5dcab..5e1fa6e8 100644
--- a/src/Filee.App/Assets/i18n/es.json
+++ b/src/Filee.App/Assets/i18n/es.json
@@ -90,6 +90,7 @@
"error.needs_shaping": "Este sistema de escritura necesita LibreOffice para convertirse bien. Instálalo en Ajustes → Motores",
"error.runtime_missing": "Falta un archivo del runtime de Microsoft Visual C++ que necesita este motor, o está desactualizado. Actualiza o reinstala Filee, o instala Microsoft Visual C++ Redistributable (x64)",
"error.conversion_failed": "El motor devolvió un error",
+ "error.pdf_password_gone": "La contraseña de PDF del ajuste no se guarda en el historial, y el ajuste ya no la tiene. Vuelve a convertir los archivos con un ajuste que tenga la contraseña.",
"error.web_download_failed": "No se pudo descargar el archivo",
"error.web_page": "El enlace abre una página web, no un archivo. Filee no puede descargar un archivo que requiere iniciar sesión: guárdalo primero desde el navegador",
"error.web_too_large": "El archivo supera los 2 GB",
@@ -530,7 +531,7 @@
"presets.watermark": "Marca de agua",
"presets.watermark_hint": "p. ej., BORRADOR",
"presets.pdf_password": "Contraseña para abrir",
- "presets.pdf_password_hint": "Vacío para ninguna. Se guarda con el ajuste preestablecido: úsala solo para este tipo de archivo.",
+ "presets.pdf_password_hint": "Vacío para ninguna. Se guarda con el ajuste preestablecido: úsala solo para este tipo de archivo. Un PDF/A no puede tener contraseña, así que se desactiva mientras PDF/A esté marcado.",
"presets.page_numbers": "Números de página (1 / 5 abajo)",
"presets.combine_pages_hint": "Pone todas las páginas una debajo de otra en una sola imagen.\nLos resultados muy largos se escalan al límite del formato (JPG 65 500 px, WebP 16 383 px).",
"presets.combine_pages": "Apilar las páginas en una imagen alta (cuando se convierte un PDF)",
diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.json
index e2725034..ce3ebe45 100644
--- a/src/Filee.App/Assets/i18n/fr.json
+++ b/src/Filee.App/Assets/i18n/fr.json
@@ -96,6 +96,7 @@
"error.needs_shaping": "Cette écriture nécessite LibreOffice pour être convertie correctement. Installez-le dans Paramètres → Moteurs",
"error.runtime_missing": "Un fichier du runtime Microsoft Visual C++ requis par ce moteur est manquant ou obsolète. Mettez à jour ou réinstallez Filee, ou installez Microsoft Visual C++ Redistributable (x64)",
"error.conversion_failed": "Le moteur a signalé une erreur",
+ "error.pdf_password_gone": "Le mot de passe PDF du préréglage n'est pas gardé dans l'historique, et le préréglage n'en a plus. Convertissez à nouveau les fichiers avec un préréglage qui a le mot de passe.",
"error.web_download_failed": "Impossible de télécharger le fichier",
"error.web_page": "Le lien ouvre une page web, pas un fichier. Filee ne peut pas télécharger un fichier qui exige une connexion : enregistrez-le d'abord depuis le navigateur",
"error.web_too_large": "Le fichier dépasse 2 Go",
@@ -545,7 +546,7 @@
"presets.watermark": "Filigrane",
"presets.watermark_hint": "p. ex. BROUILLON",
"presets.pdf_password": "Mot de passe d'ouverture",
- "presets.pdf_password_hint": "Vide pour aucun. Il est enregistré avec le préréglage : utilisez-en un réservé à ce type de fichier.",
+ "presets.pdf_password_hint": "Vide pour aucun. Il est enregistré avec le préréglage : utilisez-en un réservé à ce type de fichier. Un PDF/A ne peut pas avoir de mot de passe : ce champ est désactivé tant que PDF/A est coché.",
"presets.page_numbers": "Numéros de page (1 / 5 en bas)",
"presets.combine_pages_hint": "Place toutes les pages les unes sous les autres dans une seule image.\nLes résultats très longs sont réduits à la limite du format (JPG 65 500 px, WebP 16 383 px).",
"presets.combine_pages": "Empiler les pages en une seule image haute (lors de la conversion d'un PDF)",
diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json
index ab0f3743..8d59121e 100644
--- a/src/Filee.App/Assets/i18n/hi.json
+++ b/src/Filee.App/Assets/i18n/hi.json
@@ -90,6 +90,7 @@
"error.needs_shaping": "इस लिपि को सही ढंग से कन्वर्ट करने के लिए LibreOffice चाहिए। इसे सेटिंग्स → इंजन में इंस्टॉल करें",
"error.runtime_missing": "इस इंजन के लिए ज़रूरी Microsoft Visual C++ रनटाइम फ़ाइल नहीं मिली या पुरानी है। Filee को अपडेट करें या फिर से इंस्टॉल करें, या Microsoft Visual C++ Redistributable (x64) इंस्टॉल करें",
"error.conversion_failed": "इंजन ने एक त्रुटि बताई",
+ "error.pdf_password_gone": "प्रीसेट का PDF पासवर्ड इतिहास में नहीं रखा जाता, और प्रीसेट में अब पासवर्ड नहीं है। पासवर्ड वाले प्रीसेट से फ़ाइलें फिर से बदलें।",
"error.web_download_failed": "फ़ाइल डाउनलोड नहीं हो सकी",
"error.web_page": "यह लिंक फ़ाइल नहीं, एक वेब पेज खोलता है। जिस फ़ाइल के लिए साइन-इन ज़रूरी है उसे Filee डाउनलोड नहीं कर सकता: पहले उसे ब्राउज़र से सेव करें",
"error.web_too_large": "फ़ाइल 2 GB से बड़ी है",
@@ -530,7 +531,7 @@
"presets.watermark": "वॉटरमार्क",
"presets.watermark_hint": "जैसे: ड्राफ्ट",
"presets.pdf_password": "खोलने का पासवर्ड",
- "presets.pdf_password_hint": "खाली छोड़ें तो कोई पासवर्ड नहीं। यह प्रीसेट के साथ सेव होता है, इसलिए सिर्फ़ इस तरह की फ़ाइलों का पासवर्ड रखें।",
+ "presets.pdf_password_hint": "खाली छोड़ें तो कोई पासवर्ड नहीं। यह प्रीसेट के साथ सेव होता है, इसलिए सिर्फ़ इस तरह की फ़ाइलों का पासवर्ड रखें। PDF/A में पासवर्ड नहीं हो सकता, इसलिए PDF/A चुना हो तो यह बंद रहता है।",
"presets.page_numbers": "पेज नंबर (नीचे 1 / 5)",
"presets.combine_pages_hint": "सभी पेजों को एक के नीचे एक रखकर एक इमेज बनाता है।\nबहुत लंबे नतीजे फ़ॉर्मैट की सीमा तक स्केल किए जाते हैं (JPG 65,500 px, WebP 16,383 px)।",
"presets.combine_pages": "पेजों को एक लंबी इमेज में जोड़ें (जब PDF कन्वर्ट हो)",
diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json
index 8c316463..4f8bd01d 100644
--- a/src/Filee.App/Assets/i18n/ja.json
+++ b/src/Filee.App/Assets/i18n/ja.json
@@ -90,6 +90,7 @@
"error.needs_shaping": "この文字体系の文書を正しく変換するにはLibreOfficeが必要です。「設定」→「変換エンジン」でインストールしてください",
"error.runtime_missing": "このエンジンに必要なMicrosoft Visual C++ランタイムのファイルがないか、古くなっています。Filee を更新または再インストールするか、Microsoft Visual C++ 再頒布可能パッケージ(x64)をインストールしてください",
"error.conversion_failed": "変換エンジンからエラーが報告されました",
+ "error.pdf_password_gone": "プリセットの PDF パスワードは履歴に保存されず、プリセットにも残っていません。パスワードのあるプリセットでもう一度変換してください。",
"error.web_download_failed": "ファイルをダウンロードできませんでした",
"error.web_page": "リンク先はファイルではなくWebページです。ログインが必要なファイルは Filee ではダウンロードできないため、先にブラウザーで保存してください",
"error.web_too_large": "ファイルが2 GBを超えています",
@@ -530,7 +531,7 @@
"presets.watermark": "透かし",
"presets.watermark_hint": "例:下書き",
"presets.pdf_password": "開くときのパスワード",
- "presets.pdf_password_hint": "空欄なら設定しません。プリセットと一緒に保存されるので、この用途専用のパスワードにしてください。",
+ "presets.pdf_password_hint": "空欄なら設定しません。プリセットと一緒に保存されるので、この用途専用のパスワードにしてください。 PDF/A にはパスワードを設定できないため、PDF/A がオンのときは無効になります。",
"presets.page_numbers": "ページ番号(下部に 1 / 5)",
"presets.combine_pages_hint": "すべてのページを縦に並べて1枚の画像にします。\n長すぎる場合は形式の上限に合わせて縮小されます(JPG:65,500 px、WebP:16,383 px)。",
"presets.combine_pages": "ページを縦に並べて1枚の画像にする(PDFを変換する場合)",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index dfdf555b..7bafc85c 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -96,6 +96,7 @@
"error.needs_shaping": "이 문자는 LibreOffice가 있어야 제대로 변환돼요. 설정 → 변환 엔진에서 설치해 주세요",
"error.runtime_missing": "이 엔진에 필요한 Microsoft Visual C++ 런타임 파일이 없거나 오래됐어요. Filee를 업데이트하거나 다시 설치하거나, Microsoft Visual C++ 재배포 가능 패키지(x64)를 설치해 주세요",
"error.conversion_failed": "엔진에서 오류가 발생했어요",
+ "error.pdf_password_gone": "프리셋의 PDF 암호는 기록에 남기지 않으며, 프리셋에도 더 이상 암호가 없습니다. 암호가 있는 프리셋으로 다시 변환하세요.",
"error.web_download_failed": "파일을 내려받지 못했어요",
"error.web_page": "링크가 파일이 아니라 웹페이지로 열려요. 로그인이 필요한 파일은 Filee가 내려받을 수 없으니 브라우저에서 먼저 저장해 주세요",
"error.web_too_large": "2GB보다 큰 파일이에요",
@@ -545,7 +546,7 @@
"presets.watermark": "워터마크",
"presets.watermark_hint": "예: 초안",
"presets.pdf_password": "열기 암호",
- "presets.pdf_password_hint": "비워 두면 암호를 걸지 않습니다. 프리셋과 함께 저장되므로 이 용도로만 쓰는 암호를 넣으세요.",
+ "presets.pdf_password_hint": "비워 두면 암호를 걸지 않습니다. 프리셋과 함께 저장되므로 이 용도로만 쓰는 암호를 넣으세요. PDF/A에는 암호를 걸 수 없으므로 PDF/A를 켜면 이 칸은 꺼집니다.",
"presets.page_numbers": "페이지 번호 (아래쪽에 1 / 5)",
"presets.combine_pages_hint": "모든 페이지를 위아래로 이어 이미지 한 장으로 만들어요.\n너무 길면 형식의 최대 높이에 맞게 줄여요(JPG 65,500px, WebP 16,383px).",
"presets.combine_pages": "모든 페이지를 세로로 이어 한 장으로 (PDF를 변환할 때)",
diff --git a/src/Filee.App/Assets/i18n/ne.json b/src/Filee.App/Assets/i18n/ne.json
index 11ac1440..da4a9ef7 100644
--- a/src/Filee.App/Assets/i18n/ne.json
+++ b/src/Filee.App/Assets/i18n/ne.json
@@ -90,6 +90,7 @@
"error.needs_shaping": "यस लिपिलाई सही रूपमा रूपान्तरण गर्न LibreOffice आवश्यक पर्दछ। यसलाई सेटिङहरू → इन्जिनहरूमा स्थापना गर्नुहोस्",
"error.runtime_missing": "यो इन्जिनलाई आवश्यक पर्ने Microsoft Visual C++ रनटाइम फाइल फेला परेन वा पुरानो भयो। Filee लाई अपडेट वा पुन: स्थापना गर्नुहोस्, वा Microsoft Visual C++ Redistributable (x64) स्थापना गर्नुहोस्",
"error.conversion_failed": "इन्जिनले त्रुटि रिपोर्ट गर्‍यो",
+ "error.pdf_password_gone": "प्रिसेटको PDF पासवर्ड इतिहासमा राखिँदैन, र प्रिसेटमा अब पासवर्ड छैन। पासवर्ड भएको प्रिसेटले फाइलहरू फेरि रूपान्तरण गर्नुहोस्।",
"error.web_download_failed": "फाइल डाउनलोड गर्न सकिएन",
"error.web_page": "लिङ्कले फाइल नभई वेब पृष्ठ खोल्छ। साइन-इन आवश्यक पर्ने फाइल Filee ले डाउनलोड गर्न सक्दैन: पहिले यसलाई ब्राउजरबाट सुरक्षित गर्नुहोस्",
"error.web_too_large": "फाइल २ GB भन्दा ठूलो छ",
@@ -530,7 +531,7 @@
"presets.watermark": "वाटरमार्क",
"presets.watermark_hint": "जस्तै: मस्यौदा",
"presets.pdf_password": "खोल्ने पासवर्ड",
- "presets.pdf_password_hint": "पासवर्ड नचाहिए खाली छोड्नुहोस्। यो प्रिसेटसँगै सेभ हुन्छ, त्यसैले यस्तै फाइलका लागि मात्र छुट्टै पासवर्ड प्रयोग गर्नुहोस्।",
+ "presets.pdf_password_hint": "पासवर्ड नचाहिए खाली छोड्नुहोस्। यो प्रिसेटसँगै सेभ हुन्छ, त्यसैले यस्तै फाइलका लागि मात्र छुट्टै पासवर्ड प्रयोग गर्नुहोस्। PDF/A मा पासवर्ड राख्न मिल्दैन, त्यसैले PDF/A छानिएको बेला यो बन्द हुन्छ।",
"presets.page_numbers": "पृष्ठ नम्बर (तल 1 / 5)",
"presets.combine_pages_hint": "सबै पृष्ठहरूलाई एउटै छविमा एकपछि अर्को तल राख्छ।\nधेरै लामा परिणामहरू ढाँचाको सीमासम्म घटाइन्छ (JPG ६५,५०० px, WebP १६,३८३ px)।",
"presets.combine_pages": "पृष्ठहरूलाई एउटै लामो छविमा मिलाउनुहोस् (जब PDF रूपान्तरण हुन्छ)",
diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json
index 202019b2..73f37f24 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -96,6 +96,7 @@
"error.needs_shaping": "To pismo wymaga LibreOffice do poprawnej konwersji. Zainstaluj go w Ustawienia → Silniki",
"error.runtime_missing": "Brakuje pliku środowiska Microsoft Visual C++ potrzebnego temu silnikowi albo jest on nieaktualny. Zaktualizuj lub zainstaluj ponownie Filee albo zainstaluj Microsoft Visual C++ Redistributable (x64)",
"error.conversion_failed": "Silnik zgłosił błąd",
+ "error.pdf_password_gone": "Hasło PDF ustawienia nie jest zapisywane w historii, a ustawienie już go nie ma. Przekonwertuj pliki ponownie ustawieniem z hasłem.",
"error.web_download_failed": "Nie udało się pobrać pliku",
"error.web_page": "Link otwiera stronę internetową, a nie plik. Filee nie pobierze pliku, który wymaga zalogowania: najpierw zapisz go w przeglądarce",
"error.web_too_large": "Plik jest większy niż 2 GB",
@@ -545,7 +546,7 @@
"presets.watermark": "Znak wodny",
"presets.watermark_hint": "np. SZKIC",
"presets.pdf_password": "Hasło do otwarcia",
- "presets.pdf_password_hint": "Puste oznacza brak hasła. Zapisuje się razem z ustawieniem, więc użyj hasła tylko do tego rodzaju plików.",
+ "presets.pdf_password_hint": "Puste oznacza brak hasła. Zapisuje się razem z ustawieniem, więc użyj hasła tylko do tego rodzaju plików. PDF/A nie może mieć hasła, więc to pole jest wyłączone, gdy zaznaczono PDF/A.",
"presets.page_numbers": "Numery stron (1 / 5 na dole)",
"presets.combine_pages_hint": "Układa wszystkie strony jedna pod drugą w jednym obrazie.\nBardzo długie wyniki są skalowane do limitu formatu (JPG 65 500 px, WebP 16 383 px).",
"presets.combine_pages": "Złóż strony w jeden wysoki obraz (przy konwersji PDF)",
diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.json
index 114685b2..b22dae23 100644
--- a/src/Filee.App/Assets/i18n/pt-BR.json
+++ b/src/Filee.App/Assets/i18n/pt-BR.json
@@ -96,6 +96,7 @@
"error.needs_shaping": "Este alfabeto precisa do LibreOffice para converter corretamente. Instale-o em Configurações → Motores",
"error.runtime_missing": "Falta um arquivo do tempo de execução do Microsoft Visual C++ que este motor precisa, ou ele está desatualizado. Atualize ou reinstale o Filee, ou instale o Microsoft Visual C++ Redistributable (x64)",
"error.conversion_failed": "O motor informou um erro",
+ "error.pdf_password_gone": "A senha de PDF da predefinição não fica no histórico, e a predefinição não tem mais uma. Converta os arquivos de novo com uma predefinição que tenha a senha.",
"error.web_download_failed": "Não foi possível baixar o arquivo",
"error.web_page": "O link abre uma página da web, não um arquivo. O Filee não baixa um arquivo que exige login: salve-o no navegador primeiro",
"error.web_too_large": "O arquivo é maior que 2 GB",
@@ -545,7 +546,7 @@
"presets.watermark": "Marca d'água",
"presets.watermark_hint": "ex.: RASCUNHO",
"presets.pdf_password": "Senha para abrir",
- "presets.pdf_password_hint": "Vazio para nenhuma. Ela é salva com a predefinição, então use uma só para esse tipo de arquivo.",
+ "presets.pdf_password_hint": "Vazio para nenhuma. Ela é salva com a predefinição, então use uma só para esse tipo de arquivo. Um PDF/A não pode ter senha, então este campo fica desativado enquanto PDF/A estiver marcado.",
"presets.page_numbers": "Números de página (1 / 5 embaixo)",
"presets.combine_pages_hint": "Coloca todas as páginas uma embaixo da outra numa única imagem.\nResultados muito longos são reduzidos ao limite do formato (JPG 65.500 px, WebP 16.383 px).",
"presets.combine_pages": "Empilhar as páginas numa imagem alta (quando um PDF é convertido)",
diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json
index e855b4d7..01d58915 100644
--- a/src/Filee.App/Assets/i18n/ru.json
+++ b/src/Filee.App/Assets/i18n/ru.json
@@ -96,6 +96,7 @@
"error.needs_shaping": "Чтобы правильно сконвертировать текст в этой системе письма, нужен LibreOffice. Установите его в разделе «Настройки → Движки»",
"error.runtime_missing": "Не хватает файла среды выполнения Microsoft Visual C++, нужного этому движку, или он устарел. Обновите или переустановите Filee либо установите Microsoft Visual C++ Redistributable (x64)",
"error.conversion_failed": "Движок сообщил об ошибке",
+ "error.pdf_password_gone": "Пароль PDF из пресета не хранится в истории, а в пресете его больше нет. Конвертируйте файлы снова пресетом с паролем.",
"error.web_download_failed": "Не удалось скачать файл",
"error.web_page": "Ссылка ведёт на веб-страницу, а не на файл. Файл, для которого нужен вход в аккаунт, Filee скачать не может: сначала сохраните его в браузере",
"error.web_too_large": "Файл больше 2 ГБ",
@@ -545,7 +546,7 @@
"presets.watermark": "Водяной знак",
"presets.watermark_hint": "например, ЧЕРНОВИК",
"presets.pdf_password": "Пароль для открытия",
- "presets.pdf_password_hint": "Пусто — без пароля. Он сохраняется вместе с пресетом, поэтому используйте отдельный пароль только для таких файлов.",
+ "presets.pdf_password_hint": "Пусто — без пароля. Он сохраняется вместе с пресетом, поэтому используйте отдельный пароль только для таких файлов. У PDF/A не может быть пароля, поэтому поле отключено, пока отмечен PDF/A.",
"presets.page_numbers": "Номера страниц (1 / 5 внизу)",
"presets.combine_pages_hint": "Ставит все страницы одну под другой в одной картинке.\nОчень длинный результат уменьшается до предела формата (JPG 65 500 px, WebP 16 383 px).",
"presets.combine_pages": "Сложить страницы в одну длинную картинку (при конвертации PDF)",
diff --git a/src/Filee.App/Assets/i18n/th.json b/src/Filee.App/Assets/i18n/th.json
index 1bcc6e2a..d4ca8317 100644
--- a/src/Filee.App/Assets/i18n/th.json
+++ b/src/Filee.App/Assets/i18n/th.json
@@ -90,6 +90,7 @@
"error.needs_shaping": "ภาษานี้ต้องใช้ LibreOffice เพื่อแปลงให้ถูกต้อง ติดตั้งได้ในการตั้งค่า → เครื่องมือแปลงไฟล์",
"error.runtime_missing": "ไฟล์รันไทม์ Microsoft Visual C++ ที่เครื่องมือนี้ต้องใช้ขาดหายไปหรือล้าสมัย โปรดอัปเดตหรือติดตั้ง Filee ใหม่ หรือติดตั้ง Microsoft Visual C++ Redistributable (x64)",
"error.conversion_failed": "เครื่องมือแปลงไฟล์รายงานข้อผิดพลาด",
+ "error.pdf_password_gone": "ประวัติไม่ได้เก็บรหัสผ่าน PDF ของพรีเซ็ตไว้ และพรีเซ็ตก็ไม่มีรหัสผ่านแล้ว แปลงไฟล์อีกครั้งด้วยพรีเซ็ตที่มีรหัสผ่าน",
"error.web_download_failed": "ไม่สามารถดาวน์โหลดไฟล์ได้",
"error.web_page": "ลิงก์นี้เปิดหน้าเว็บ ไม่ใช่ไฟล์ Filee ไม่สามารถดาวน์โหลดไฟล์ที่ต้องเข้าสู่ระบบได้ โปรดบันทึกจากเบราว์เซอร์ก่อน",
"error.web_too_large": "ไฟล์มีขนาดใหญ่กว่า 2 GB",
@@ -530,7 +531,7 @@
"presets.watermark": "ลายน้ำ",
"presets.watermark_hint": "เช่น ฉบับร่าง",
"presets.pdf_password": "รหัสผ่านสำหรับเปิด",
- "presets.pdf_password_hint": "เว้นว่างไว้หากไม่ต้องการ รหัสผ่านจะถูกบันทึกไว้กับพรีเซ็ต จึงควรใช้รหัสผ่านสำหรับไฟล์ประเภทนี้เท่านั้น",
+ "presets.pdf_password_hint": "เว้นว่างไว้หากไม่ต้องการ รหัสผ่านจะถูกบันทึกไว้กับพรีเซ็ต จึงควรใช้รหัสผ่านสำหรับไฟล์ประเภทนี้เท่านั้น PDF/A ใส่รหัสผ่านไม่ได้ ช่องนี้จึงปิดอยู่เมื่อเลือก PDF/A",
"presets.page_numbers": "เลขหน้า (1 / 5 ที่ด้านล่าง)",
"presets.combine_pages_hint": "เรียงทุกหน้าต่อกันในแนวดิ่งเป็นภาพเดียว\nผลลัพธ์ที่ยาวมากจะถูกปรับขนาดไม่ให้เกินขีดจำกัดของฟอร์แมต (JPG 65,500 px, WebP 16,383 px)",
"presets.combine_pages": "ต่อหน้าเป็นภาพแนวยาวภาพเดียว (เมื่อแปลง PDF)",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index 1a16cd1f..7caee944 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -96,6 +96,7 @@
"error.needs_shaping": "这种文字需要 LibreOffice 才能正确转换,请在“设置 → 转换引擎”中安装",
"error.runtime_missing": "此引擎所需的 Microsoft Visual C++ 运行库文件缺失或版本过旧。请更新或重新安装 Filee,或安装 Microsoft Visual C++ 可再发行程序包 (x64)",
"error.conversion_failed": "转换引擎出错",
+ "error.pdf_password_gone": "历史记录不保存预设的 PDF 密码,而该预设已没有密码。请用带密码的预设重新转换这些文件。",
"error.web_download_failed": "无法下载该文件",
"error.web_page": "该链接打开的是网页,不是文件。需要登录才能获取的文件 Filee 无法下载,请先在浏览器中保存",
"error.web_too_large": "文件大于 2 GB",
@@ -545,7 +546,7 @@
"presets.watermark": "水印",
"presets.watermark_hint": "例如:草稿",
"presets.pdf_password": "打开密码",
- "presets.pdf_password_hint": "留空则不设密码。密码会随预设一起保存,请只用于这类文件。",
+ "presets.pdf_password_hint": "留空则不设密码。密码会随预设一起保存,请只用于这类文件。PDF/A 不能设密码,因此勾选 PDF/A 时此项不可用。",
"presets.page_numbers": "页码(底部显示 1 / 5)",
"presets.combine_pages_hint": "把所有页面上下相接,生成一张图片。\n过长时会缩小到该格式的最大高度(JPG 65,500 像素,WebP 16,383 像素)。",
"presets.combine_pages": "把所有页面上下拼成一张长图(转换 PDF 时)",
diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.json
index 40e6ef61..ad8a9bc2 100644
--- a/src/Filee.App/Assets/i18n/zh-TW.json
+++ b/src/Filee.App/Assets/i18n/zh-TW.json
@@ -96,6 +96,7 @@
"error.needs_shaping": "這種文字需要 LibreOffice 才能正確轉換,請在「設定 → 轉換引擎」中安裝",
"error.runtime_missing": "此引擎所需的 Microsoft Visual C++ 執行階段程式庫檔案缺失或版本過舊。請更新或重新安裝 Filee,或安裝 Microsoft Visual C++ 可轉散發套件 (x64)",
"error.conversion_failed": "轉換引擎出錯",
+ "error.pdf_password_gone": "歷史記錄不保存預設的 PDF 密碼,而該預設已沒有密碼。請用有密碼的預設重新轉換這些檔案。",
"error.web_download_failed": "無法下載該檔案",
"error.web_page": "該連結開啟的是網頁,不是檔案。需要登入才能獲取的檔案 Filee 無法下載,請先在瀏覽器中儲存",
"error.web_too_large": "檔案大於 2 GB",
@@ -545,7 +546,7 @@
"presets.watermark": "浮水印",
"presets.watermark_hint": "例如:草稿",
"presets.pdf_password": "開啟密碼",
- "presets.pdf_password_hint": "留空則不設密碼。密碼會隨預設一起儲存,請只用於這類檔案。",
+ "presets.pdf_password_hint": "留空則不設密碼。密碼會隨預設一起儲存,請只用於這類檔案。PDF/A 不能設密碼,因此勾選 PDF/A 時此欄不可用。",
"presets.page_numbers": "頁碼(底部顯示 1 / 5)",
"presets.combine_pages_hint": "把所有頁面上下相接,產生一張圖片。\n過長時會縮小到該格式的最大高度(JPG 65,500 像素,WebP 16,383 像素)。",
"presets.combine_pages": "把所有頁面上下拼成一張長圖(轉換 PDF 時)",
diff --git a/src/Filee.App/Services/ConversionService.cs b/src/Filee.App/Services/ConversionService.cs
index 54f114f9..44b0c0fd 100644
--- a/src/Filee.App/Services/ConversionService.cs
+++ b/src/Filee.App/Services/ConversionService.cs
@@ -107,6 +107,13 @@ public sealed class ConversionService
var files = sources.Where(Exists).Distinct(StringComparer.Ordinal).ToList();
if (files.Count == 0)
return null;
+ // History keeps no PDF password: it comes from the preset when that still has one (else the job refuses).
+ if (preset.Pdf.PasswordLeftOut && _store.FindPreset(preset.Id)?.Pdf.Password is { Length: > 0 } password)
+ {
+ preset = preset.Clone();
+ preset.Pdf.Password = password;
+ preset.Pdf.PasswordLeftOut = false;
+ }
if (watchRuleId is not null && WatchRetry is { } watchRetry)
{
_ = watchRetry(watchRuleId, files, preset);
diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
index bdbe5f1a..6c9120bb 100644
--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
@@ -396,6 +396,18 @@ public sealed partial class PresetEditorViewModel : ObservableObject
[ObservableProperty] private bool _pageNumbers;
[ObservableProperty] private string _pdfPassword;
+ /// <summary>AES-256 readers use at most 127 UTF-8 bytes of a password: the box takes no more.</summary>
+ internal const int MaxPasswordBytes = 127;
+
+ partial void OnPdfPasswordChanged(string value)
+ {
+ if (System.Text.Encoding.UTF8.GetByteCount(value) <= MaxPasswordBytes)
+ return;
+ var bytes = 0;
+ var fits = string.Concat(value.EnumerateRunes().TakeWhile(r => (bytes += r.Utf8SequenceLength) <= MaxPasswordBytes));
+ PdfPassword = fits;
+ }
+
/// <summary>PDF → image: one tall image of all pages.</summary>
[ObservableProperty] private bool _combinePages;
[ObservableProperty] private bool _trimPageMargins;
@@ -616,7 +628,9 @@ public sealed partial class PresetEditorViewModel : ObservableObject
// Only for a PDF target, where they are shown: a password left behind by it must not lock nothing.
pdf.Watermark = ShowPdfBuild ? Watermark.Trim() : "";
pdf.PageNumbers = ShowPdfBuild && PageNumbers;
- pdf.Password = ShowPdfBuild ? PdfPassword : "";
+ // PDF/A can't be encrypted, so the box is off while it is ticked.
+ pdf.Password = ShowPdfBuild && !PdfA ? PdfPassword : "";
+ pdf.PasswordLeftOut = false;
_original.Document.PdfA = PdfA;
// Only where the option is shown, as with SaveEveryFrame below.
_original.Document.LeaveOutPictures = ShowLeaveOutPictures && LeaveOutPictures;
diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axaml
index 76005435..9b99d0fc 100644
--- a/src/Filee.App/Views/PresetEditorView.axaml
+++ b/src/Filee.App/Views/PresetEditorView.axaml
@@ -375,7 +375,8 @@
</StackPanel>
<StackPanel Grid.Column="2">
<TextBlock Classes="label" Text="{DynamicResource presets.pdf_password}" />
- <TextBox Text="{Binding PdfPassword}" PasswordChar="•" Classes="revealPasswordButton" MaxLength="64" />
+ <TextBox Text="{Binding PdfPassword}" PasswordChar="•" Classes="revealPasswordButton" MaxLength="64"
+ IsEnabled="{Binding !PdfA}" />
</StackPanel>
</Grid>
<TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource presets.pdf_password_hint}" />
diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.cs
index 6df26c33..f8bb377d 100644
--- a/src/Filee.Core/Conversion/JobQueue.cs
+++ b/src/Filee.Core/Conversion/JobQueue.cs
@@ -232,16 +232,19 @@ public sealed class JobQueue : IAsyncDisposable
}
}
- /// <summary>Converts every file to PDF in the work directory, then merges them into one output.</summary>
/// <summary>Applies the preset's PDF finishing (<see cref="PdfOptions.FinishesPdf"/>) to the PDFs among <paramref name="outputs"/>.</summary>
private async Task FinishPdfsAsync(Preset preset, IReadOnlyList<string> outputs, CancellationToken ct)
{
+ // A retry from history whose preset (and so its password) is gone: no PDF without the password it was meant to have.
+ if (preset.Pdf.PasswordLeftOut && preset.Pdf.Password.Length == 0)
+ throw new ConversionRefusedException("error.pdf_password_gone");
if (!preset.Pdf.FinishesPdf || _catalog.All.OfType<IPdfFinisher>().FirstOrDefault() is not { } finisher)
return;
foreach (var pdf in outputs.Where(o => FormatRegistry.Detect(o)?.Id == "pdf"))
await finisher.FinishAsync(pdf, preset.Pdf, ct);
}
+ /// <summary>Converts every file to PDF in the work directory, then merges them into one output.</summary>
private async Task RunMergedAsync(ConversionJob job, RoutePlanner planner, string workDir)
{
var parts = new string?[job.Files.Count];
diff --git a/src/Filee.Core/History/HistoryEntry.cs b/src/Filee.Core/History/HistoryEntry.cs
index 6718a9b8..e9bca316 100644
--- a/src/Filee.Core/History/HistoryEntry.cs
+++ b/src/Filee.Core/History/HistoryEntry.cs
@@ -24,7 +24,8 @@ public sealed class HistoryEntry
/// <summary>
/// The preset as the job ran it (save location already decided, a watch folder's output folder included), kept
- /// when files failed: they can be converted again the same way even after the preset was changed or deleted.
+ /// when files failed: they can be converted again the same way even after the preset was changed or deleted. Its PDF
+ /// password is left out (<see cref="PdfOptions.PasswordLeftOut"/>).
/// </summary>
public Preset? Preset { get; set; }
@@ -47,7 +48,8 @@ public sealed class HistoryEntry
Sources = [.. job.Sources],
Outputs = [.. job.Outputs],
Failures = failures,
- Preset = failures.Count > 0 ? job.Preset.Clone() : null,
+ // history.json isn't the place for a PDF password: a retry takes it from the preset again.
+ Preset = failures.Count > 0 ? job.Preset.Clone().WithoutPassword(mark: true) : null,
};
}
}
diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.cs
index 652f3815..14df409b 100644
--- a/src/Filee.Core/Presets/Preset.cs
+++ b/src/Filee.Core/Presets/Preset.cs
@@ -180,6 +180,20 @@ public sealed class Preset
public static string NewId() => Guid.NewGuid().ToString("N")[..12];
/// <summary>Deep copy, used by editors so changes can be cancelled.</summary>
+ /// <summary>
+ /// This preset without its PDF password, for copies that leave the library (history, an export).
+ /// <paramref name="mark"/> records that it was taken out (<see cref="PdfOptions.PasswordLeftOut"/>).
+ /// </summary>
+ public Preset WithoutPassword(bool mark)
+ {
+ if (Pdf.Password.Length == 0)
+ return this;
+ var copy = Clone();
+ copy.Pdf.Password = "";
+ copy.Pdf.PasswordLeftOut = mark;
+ return copy;
+ }
+
public Preset Clone() => new()
{
Id = Id,
@@ -453,9 +467,15 @@ public sealed class PdfOptions
/// </summary>
public string Password { get; set; } = "";
+ /// <summary>
+ /// The <see cref="Password"/> was left out of this copy (the one history keeps to convert failed files again): a
+ /// retry takes it from the preset again, and fails rather than write a PDF without it.
+ /// </summary>
+ public bool PasswordLeftOut { get; set; }
+
/// <summary>A PDF this preset writes gets a watermark, page numbers or a password (<see cref="Conversion.IPdfFinisher"/>).</summary>
[JsonIgnore]
- public bool FinishesPdf => !string.IsNullOrWhiteSpace(Watermark) || PageNumbers || Password.Length > 0;
+ public bool FinishesPdf => !string.IsNullOrWhiteSpace(Watermark) || PageNumbers || Password.Length > 0 || PasswordLeftOut;
public PdfOptions Clone() => (PdfOptions)MemberwiseClone();
}
diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs
index 885ddb08..77d41992 100644
--- a/src/Filee.Core/Settings/UserDataStore.cs
+++ b/src/Filee.Core/Settings/UserDataStore.cs
@@ -204,9 +204,10 @@ public sealed class UserDataStore
/// <summary>The preset <paramref name="id"/> when it converts (a group or tool doesn't), for every place that runs one.</summary>
public Preset? FindConversion(string id) => Presets.FirstOrDefault(p => p.Id == id && !p.IsGroup && !p.IsTool);
- /// <summary>Exports presets and profiles to a shareable JSON file.</summary>
+ /// <summary>Exports presets and profiles to a shareable JSON file, without PDF passwords.</summary>
public void Export(string path) =>
- Write(path, new PresetBundle { Presets = Presets, Profiles = Profiles }, FileeJsonContext.Default.PresetBundle);
+ Write(path, new PresetBundle { Presets = [.. Presets.Select(p => p.WithoutPassword(mark: false))], Profiles = Profiles },
+ FileeJsonContext.Default.PresetBundle);
/// <summary>
/// Imports presets and profiles from a bundle. Items with an existing id are replaced, new ones added.
diff --git a/src/Filee.Engines/Pdf/PdfFinishing.cs b/src/Filee.Engines/Pdf/PdfFinishing.cs
index c7308fdc..75f39cd8 100644
--- a/src/Filee.Engines/Pdf/PdfFinishing.cs
+++ b/src/Filee.Engines/Pdf/PdfFinishing.cs
@@ -15,33 +15,92 @@ internal static class PdfFinishing
{
private const double PointsPerMm = 72 / 25.4;
+ /// <summary>The most UTF-8 bytes of a password readers use (AES-256, revision 6): longer ones can't be opened.</summary>
+ public const int MaxPasswordBytes = 127;
+
/// <summary>Rewrites <paramref name="path"/> with the watermark, page numbers and password <paramref name="options"/> ask for.</summary>
public static void Finish(string path, PdfOptions options, CancellationToken ct)
{
- using (var document = PdfSharpConverter.OpenForChanges(path))
- using (var glyphs = new GlyphOutlines())
+ if (System.Text.Encoding.UTF8.GetByteCount(options.Password) > MaxPasswordBytes)
+ throw new ArgumentException($"The PDF password is longer than {MaxPasswordBytes} bytes, so PDF readers couldn't open the file with it.");
+ var finished = path + ".finished";
+ try
{
- var watermark = options.Watermark.Trim();
- for (var i = 0; i < document.PageCount; i++)
- {
- ct.ThrowIfCancellationRequested();
- var page = document.Pages[i];
- using var graphics = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append);
- if (watermark.Length > 0)
- DrawWatermark(graphics, glyphs, watermark, page.Width.Point, page.Height.Point);
- if (options.PageNumbers)
- DrawPageNumber(graphics, glyphs, $"{i + 1} / {document.PageCount}", page.Width.Point, page.Height.Point);
- }
- if (options.Password.Length > 0)
+ using (var document = PdfSharpConverter.OpenForChanges(path))
+ using (var glyphs = new GlyphOutlines())
{
- document.SecuritySettings.UserPassword = options.Password;
- document.SecuritySettings.OwnerPassword = options.Password;
- document.SecurityHandler.SetEncryptionToV5();
+ var watermark = options.Watermark.Trim();
+ for (var i = 0; i < document.PageCount; i++)
+ {
+ ct.ThrowIfCancellationRequested();
+ Stamp(document.Pages[i], glyphs, watermark, options.PageNumbers ? $"{i + 1} / {document.PageCount}" : null);
+ }
+ if (options.Password.Length > 0)
+ {
+ document.SecuritySettings.UserPassword = options.Password;
+ document.SecuritySettings.OwnerPassword = options.Password;
+ document.SecurityHandler.SetEncryptionToV5();
+ }
+ document.Save(finished);
}
- var finished = path + ".finished";
- document.Save(finished);
File.Move(finished, path, overwrite: true);
}
+ finally
+ {
+ // Nothing is left next to the user's file when saving fails.
+ File.Delete(finished);
+ }
+ }
+
+ /// <summary>
+ /// Draws the stamps on one page as it is shown: inside its crop box and the right way up for its /Rotate. The page
+ /// is drawn on unturned (PDFsharp's own handling of turned pages puts the stamps elsewhere) and turned back.
+ /// </summary>
+ private static void Stamp(PdfPage page, GlyphOutlines glyphs, string watermark, string? number)
+ {
+ if (watermark.Length == 0 && number is null)
+ return;
+ var media = page.MediaBox;
+ var crop = page.Elements.ContainsKey("/CropBox") ? page.CropBox : media;
+ // The visible part in drawing units: x from the media box's left edge, y down from its top edge.
+ var left = Math.Max(crop.X1, media.X1) - media.X1;
+ var top = media.Y2 - Math.Min(crop.Y2, media.Y2);
+ var width = Math.Min(crop.X2, media.X2) - Math.Max(crop.X1, media.X1);
+ var height = Math.Min(crop.Y2, media.Y2) - Math.Max(crop.Y1, media.Y1);
+ if (width <= 0 || height <= 0)
+ return;
+ var rotate = page.Rotate;
+ var orientation = page.Orientation;
+ page.Rotate = 0;
+ page.Orientation = PdfSharp.PageOrientation.Portrait;
+ try
+ {
+ using var graphics = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append);
+ graphics.TranslateTransform(left, top);
+ // Shown turned clockwise by /Rotate: map the shown page (x right, y down) onto the unturned one.
+ var (shownWidth, shownHeight) = (((rotate % 360) + 360) % 360) switch
+ {
+ 90 => Turn(graphics, new XMatrix(0, -1, 1, 0, 0, height), height, width),
+ 180 => Turn(graphics, new XMatrix(-1, 0, 0, -1, width, height), width, height),
+ 270 => Turn(graphics, new XMatrix(0, 1, -1, 0, width, 0), height, width),
+ _ => (width, height),
+ };
+ if (watermark.Length > 0)
+ DrawWatermark(graphics, glyphs, watermark, shownWidth, shownHeight);
+ if (number is not null)
+ DrawPageNumber(graphics, glyphs, number, shownWidth, shownHeight);
+ }
+ finally
+ {
+ page.Orientation = orientation;
+ page.Rotate = rotate;
+ }
+
+ static (double, double) Turn(XGraphics graphics, XMatrix matrix, double shownWidth, double shownHeight)
+ {
+ graphics.MultiplyTransform(matrix);
+ return (shownWidth, shownHeight);
+ }
}
/// <summary>Large, faint grey text along the page's diagonal, over the content.</summary>
diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs
index 85165c90..7720d5a1 100644
--- a/tests/Filee.App.Tests/RenderTests.cs
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@ -1150,6 +1150,28 @@ public class RenderTests
Assert.False(preset.Pdf.FinishesPdf);
}
+ [AvaloniaFact]
+ public void Preset_editor_password_fits_readers_and_is_off_with_pdfa()
+ {
+ TestServices.EnsureInitialized("en");
+ var loc = AppHost.Get<Filee.Core.Localization.ILocalizer>();
+ var preset = new Filee.Core.Presets.Preset { TargetFormat = "pdf", Name = "Locked" };
+ var vm = new PresetEditorViewModel(preset, loc);
+
+ // 54 Korean letters are 162 UTF-8 bytes; readers use 127, so the box keeps the 42 letters that fit.
+ vm.PdfPassword = new string('비', 54);
+ Assert.Equal(new string('비', 42), vm.PdfPassword);
+ vm.PdfPassword = "pässwörd";
+ Assert.Equal("pässwörd", vm.PdfPassword);
+
+ vm.PdfA = true;
+ Assert.True(vm.Apply());
+ Assert.Equal("", preset.Pdf.Password); // PDF/A can't be encrypted
+ vm.PdfA = false;
+ Assert.True(vm.Apply());
+ Assert.Equal("pässwörd", preset.Pdf.Password);
+ }
+
[AvaloniaFact]
public void Preset_editor_keeps_rotation_visible_for_pdf_and_drops_it_for_targets_that_cannot_turn()
{
diff --git a/tests/Filee.Core.Tests/PdfPasswordPrivacyTests.cs b/tests/Filee.Core.Tests/PdfPasswordPrivacyTests.cs
new file mode 100644
index 00000000..e0f4d6a8
--- /dev/null
+++ b/tests/Filee.Core.Tests/PdfPasswordPrivacyTests.cs
@@ -0,0 +1,65 @@
+// A preset's PDF password stays in the library: it is left out of history and of an export, and a retry from history
+// never writes the PDF without it.
+
+using Filee.Core.Conversion;
+using Filee.Core.History;
+using Filee.Core.Presets;
+using Filee.Core.Settings;
+
+namespace Filee.Core.Tests;
+
+public class PdfPasswordPrivacyTests
+{
+ private static Preset Locked() => new() { Id = "locked", TargetFormat = "pdf", Pdf = { Password = "secret-1234" } };
+
+ [Fact]
+ public async Task History_keeps_no_password_but_remembers_one_was_there()
+ {
+ using var dir = new TempDir();
+ await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("magick", new ConversionEdge("jpg", "pdf")) { Throw = true }]));
+ var preset = Locked();
+ var job = new ConversionJob([dir.File("a.jpg")], preset, "Test");
+ await queue.RunAsync(job);
+
+ var entry = HistoryEntry.From(job);
+
+ Assert.Equal("", entry.Preset!.Pdf.Password);
+ Assert.True(entry.Preset.Pdf.PasswordLeftOut);
+ Assert.Equal("secret-1234", preset.Pdf.Password);
+ }
+
+ [Fact]
+ public void An_export_leaves_passwords_out()
+ {
+ using var dir = new TempDir();
+ var store = new UserDataStore(dir.Path);
+ store.Load();
+ store.Presets.Add(Locked());
+ var bundle = Path.Combine(dir.Path, "bundle.json");
+
+ store.Export(bundle);
+
+ Assert.DoesNotContain("secret-1234", File.ReadAllText(bundle));
+ Assert.Equal("secret-1234", store.FindPreset("locked")!.Pdf.Password);
+ using var other = new TempDir();
+ var target = new UserDataStore(other.Path);
+ target.Load();
+ target.Import(bundle);
+ Assert.False(target.FindPreset("locked")!.Pdf.PasswordLeftOut);
+ }
+
+ [Fact]
+ public async Task A_retry_without_its_password_fails_and_writes_no_pdf()
+ {
+ using var dir = new TempDir();
+ await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("magick", new ConversionEdge("jpg", "pdf"))]));
+ var fromHistory = Locked().WithoutPassword(mark: true);
+ var job = new ConversionJob([dir.File("a.jpg")], fromHistory, "Test");
+
+ await queue.RunAsync(job);
+
+ Assert.Equal(JobState.Failed, job.State);
+ Assert.Equal("error.pdf_password_gone", job.Files[0].ErrorKey);
+ Assert.False(File.Exists(Path.Combine(dir.Path, "a.pdf")));
+ }
+}
diff --git a/tests/Filee.Engines.Tests/PdfFinishingTests.cs b/tests/Filee.Engines.Tests/PdfFinishingTests.cs
index ac2c4a63..3812a75e 100644
--- a/tests/Filee.Engines.Tests/PdfFinishingTests.cs
+++ b/tests/Filee.Engines.Tests/PdfFinishingTests.cs
@@ -5,6 +5,7 @@ using Filee.Core.Conversion;
using Filee.Core.Presets;
using Filee.Engines.Pdf;
using Filee.Engines.Vector;
+using PdfSharp.Drawing;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using PDFtoImage;
@@ -72,6 +73,79 @@ public class PdfFinishingTests(EngineFixture fx) : IClassFixture<EngineFixture>
Assert.Contains("/AESV3", await File.ReadAllTextAsync(output, System.Text.Encoding.Latin1, TestContext.Current.CancellationToken));
}
+ /// <summary>One blank A4 page, shown turned by <paramref name="rotate"/> and cut to <paramref name="inset"/> points in.</summary>
+ private static string TurnedPdf(string folder, int rotate, double inset = 0)
+ {
+ var path = Path.Combine(folder, $"turned-{rotate}-{inset}.pdf");
+ using var document = new PdfDocument();
+ var page = document.AddPage();
+ page.Rotate = rotate;
+ if (inset > 0)
+ page.CropBox = new PdfRectangle(new XPoint(inset, inset), new XPoint(page.MediaBox.X2 - inset, page.MediaBox.Y2 - inset));
+ document.Save(path);
+ return path;
+ }
+
+ [Theory]
+ [InlineData(90)]
+ [InlineData(180)]
+ [InlineData(270)]
+ public async Task Stamps_land_on_the_page_as_it_is_shown_when_it_is_turned(int rotate)
+ {
+ var pdf = TurnedPdf(fx.NewFolder(), rotate);
+
+ var job = await fx.ConvertAsync([pdf], new Preset { TargetFormat = "pdf", Pdf = { Watermark = "CONFIDENTIAL", PageNumbers = true } });
+
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ var output = job.Outputs.Single();
+ Assert.Equal(rotate, PdfReader.Open(output, PdfDocumentOpenMode.Import).Pages[0].Rotate); // still turned
+ Assert.True(Marked(output, 0, 0.4, 0.9, 0.6, 0.99) > 5, "the page number sits at the bottom of the shown page");
+ Assert.Equal(0, Marked(output, 0, 0, 0, 1, 0.1)); // nothing along the shown top edge
+ Assert.True(Marked(output, 0, 0.3, 0.4, 0.7, 0.6) > 50, "the watermark crosses the middle");
+ }
+
+ [Fact]
+ public async Task Stamps_stay_inside_a_smaller_crop_box()
+ {
+ var pdf = TurnedPdf(fx.NewFolder(), 0, inset: 100);
+
+ var job = await fx.ConvertAsync([pdf], new Preset { TargetFormat = "pdf", Pdf = { Watermark = "DRAFT", PageNumbers = true } });
+
+ Assert.Equal(JobState.Completed, job.State);
+ var output = job.Outputs.Single();
+ // PDFium shows only the crop box: the number is at its bottom, the watermark in its middle.
+ Assert.True(Marked(output, 0, 0.35, 0.88, 0.65, 0.99) > 5, "the page number is inside the crop box");
+ Assert.True(Marked(output, 0, 0.3, 0.4, 0.7, 0.6) > 50, "the watermark is centred in the crop box");
+ }
+
+ [Theory]
+ [InlineData("pässwörd")]
+ [InlineData("비밀번호입니다")]
+ public async Task A_non_ascii_password_opens_in_pdfium(string password)
+ {
+ var pdf = BlankPdf(fx.NewFolder(), 1);
+
+ var job = await fx.ConvertAsync([pdf], new Preset { TargetFormat = "pdf", Pdf = { Password = password, PageNumbers = true } });
+
+ Assert.Equal(JobState.Completed, job.State);
+ var output = job.Outputs.Single();
+ Assert.True(Marked(output, 0, 0.4, 0.9, 0.6, 0.99, password) > 5);
+ Assert.ThrowsAny<Exception>(() => Marked(output, 0, 0, 0, 1, 1, "wrong"));
+ }
+
+ [Fact]
+ public async Task A_password_too_long_for_readers_fails_and_leaves_nothing_behind()
+ {
+ var folder = fx.NewFolder();
+ var pdf = BlankPdf(folder, 1);
+ var password = new string('비', 43); // 129 UTF-8 bytes
+
+ var job = await fx.ConvertAsync([pdf], new Preset { TargetFormat = "pdf", Pdf = { Password = password } });
+
+ Assert.Equal(JobState.Failed, job.State);
+ Assert.Empty(Directory.GetFiles(folder, "*.finished", SearchOption.AllDirectories));
+ }
+
[Fact]
public void Text_in_other_scripts_has_outlines()
{