Hit an Encrypted PDF? How to Stop the Task Queue Cleanly
When building an automated document-processing pipeline, the most insidious failures are often not program crashes, but rather the silent generation of blank or
Encrypted PDFs rarely crash a pipeline. More often they produce blank or garbled output that flows downstream unnoticed. If you build automated document processing with pypdf, this guide shows how to detect encryption, check the decryption result, and stop the task queue before corrupted data spreads.
Keep the original copies of any important documents, and verify your own results against the boundaries and acceptance criteria below before you rely on them.
You will learn why is_encrypted alone is not enough, what the return values of decrypt() mean, which test cases to build, and how to write a validation workflow with clear manual-review rules.
How do you handle an encrypted PDF in a pipeline? The short answer
Read is_encrypted, call decrypt() with the password you are authorised to use, and stop the task unless the return value is 1 or 2.
| Your situation | What to do | Why |
|---|---|---|
| The file is encrypted and you have the correct password | Call decrypt(password) and continue only if it returns 1 or 2 | 1 means the user password was verified, 2 means the owner password was verified |
| The file is encrypted and the password is wrong or missing | Stop the task, raise an exception or mark it as "requires manual intervention" | A return value of 0 means decryption failed, and some metadata may still be readable while the body stays locked |
is_encrypted is True but decrypt("") returns a non-zero value | Log the case and send it for manual review | The file may be pseudo-encrypted, and skipping it automatically could break compliance policy |
| You are tempted to guess passwords | Do not do it | Bypassing protection or running weak-password dictionary attacks is strictly prohibited |
Why does encryption fail silently?
When you open an encrypted document with pypdf, no exception is raised right away. PdfReader objects usually instantiate normally. The failure appears later, when your code accesses .pages or extracts text without verifying authorisation. The workflow then continues on corrupted data, and the resulting errors can be irreversible in downstream tasks.
The correct engineering practice is:
- Check the
is_encryptedattribute immediately after reading the file. - Determine the decryption status strictly from the return value of
decrypt(). - If no valid password is provided, or verification fails, actively terminate the task.
The mechanisms of encryption detection and authorised decryption
is_encrypted is not the same as readable
pypdf requires you to call decrypt(password) with the correct password before the content is truly unlocked.
is_encryptedreturns True when the file header declares an encryption flag. It does not mean the content is unreadable.- The integer returned by
decrypt()is the deciding criterion for whether you have legitimate access.
What the return values mean
According to the official pypdf documentation:
- 0: decryption failed, due to an incorrect password or an unsupported algorithm.
- 1: the user password was verified successfully.
- 2: the owner password was verified successfully.
Many developers assume that calling decrypt lets them carry on. In practice, an incorrect password can leave some metadata readable while the document body remains locked. In a task queue, treat a non-zero status code as a mandatory precondition, not an optional step.
AES dependencies
When you work with the AES encryption algorithm, install the cryptography or pycryptodome dependency. Without it, the decryption operation fails outright.
Synthetic test cases: expected behaviour and boundary inputs
To verify your logic without relying on sensitive external files, define the following synthetic scenarios. This section describes the logic only. In production, use real samples from your own business.
Input A: correct authorisation
A PDF encrypted with AES-256 and the password "open-sesame".
- Expected output:
decrypt("open-sesame")returns 1 or 2. Subsequent access to.pagesand text extraction is safe, and the task queue flows normally.
Input B: incorrect password
The same encrypted file, but supplied with the password "wrong-pass".
- Processing:
decrypt()returns 0. Throw a business exception immediately, or mark the task "requires manual intervention". Do not make further calls to.pages. - Some older pypdf versions allow access to certain metadata. Treat this as an unauthorised state anyway, to prevent data leakage.
Input C: pseudo-encryption or empty password
The file header is encrypted but provides no real content protection. This is rare but possible.
- Processing:
is_encryptedis True, butdecrypt("")may return a non-zero value. Handle the file under the encryption procedure, because it is formally an encrypted document. Skipping it automatically may violate compliance policy. Log the case and have someone review it to decide whether the file is simply mislabelled.
📊 At a glance
| Test input | What decrypt() returns | Action |
|---|---|---|
| A: correct password | 1 or 2 | Continue processing |
| B: incorrect password | 0 | Throw an exception or mark for manual intervention; make no further calls to .pages |
| C: empty password on pseudo-encrypted file | Non-zero (may occur) | Log and send for manual review |
Python validation script: an encryption detection workflow in memory
The following code shows how to detect encryption status securely in memory, without disk I/O or dependence on external files. It is for educational demonstration only and has not been run in a real production environment. Before you use it, install pypdf and an AES support library such as cryptography in your own locked dependency environment.
from io import BytesIO
from pypdf import PdfReader, PdfWriter
def create_encrypted_pdf_in_memory(password: str) -> bytes:
"""仅用于测试的加密PDF生成器,生产环境请替换为真实文件流"""
writer = PdfWriter()
writer.add_blank_page(width=200, height=200)
# 推荐使用AES-256,避免使用不安全的RC4
writer.encrypt(password, algorithm="AES-256")
buffer = BytesIO()
writer.write(buffer)
return buffer.getvalue()
# 模拟任务队列中的加密检测钩子
sample_pdf_bytes = create_encrypted_pdf_in_memory("test-pass")
reader = PdfReader(BytesIO(sample_pdf_bytes))
if reader.is_encrypted:
decrypt_status = reader.decrypt("test-pass")
if decrypt_status == 0:
raise PermissionError("解密失败:密码错误或权限不足,任务已拦截")
elif decrypt_status in (1, 2):
print(f"解密成功(状态:{decrypt_status}),允许进入下游处理")
else:
raise ValueError(f"未知的解密状态码: {decrypt_status}")
else:
print("文件未加密,直接处理")
# 边界验证:错误密码应返回0
bad_reader = PdfReader(BytesIO(sample_pdf_bytes))
assert bad_reader.decrypt("wrong") == 0, "错误密码必须返回0"
This script contains the core compliance-checking logic. In real projects, extract the if reader.is_encrypted blocks into independent pre-processing middleware. That way, every document entering the parsing stage has passed authorisation checks.
Acceptance criteria and manual review boundaries
Use this table to decide what happens to each observation.
| Observation | Processing decision | Note |
|---|---|---|
is_encrypted=True and no password was provided | Suspend the task and mark it "pending authorisation" | Do not attempt a blank password or a common password dictionary |
decrypt() returns 0 | Mark the task as failed; record a password hash, not the plaintext | Possible causes: incorrect password, unsupported algorithm, or missing AES dependency |
decrypt() returns 1 or 2, but .pages raises an exception | Transfer to human review | Possible causes: file corruption, special permission restrictions, or a pypdf version compatibility issue |
| No encryption flag, but the contents are unreadable | Treat as a parsing failure under normal conditions | This is not a cryptography issue; follow the general fault-tolerance procedure |
| RC4 encryption, and decryption succeeds | Allow processing, but log a warning | RC4 is proven insecure; ask the source side to upgrade to AES-256 |
decrypt("") returns a non-zero value | Mark as "pseudo-encryption" and review manually | Automatic release is not recommended, so that compliance audits do not miss anything |
This table covers code-level encryption status checks only. It is not an end-to-end quality acceptance test for translation. If a document contains scanned images, complex formatting, or mixed languages, decryption success does not guarantee accurate output. Sample the results manually to check the translated text. The code shows whether a file can be legally read. It does not confirm that the content is semantically correct.
Checklist for document translation
File splitting, encryption handling and attachment handling are part of delivery preparation. Translation cannot replace these checks.
- Keep the original documents and your processing checklist.
- Check the translated manuscript's page order.
- Check hyperlinks.
- Check content integrity against the source.
OmniDoc translates PDF, Word, PowerPoint and Excel files: scanned pages are recognized first, table cells are translated one by one so tables keep their rows and columns, and a PDF comes back as both a bilingual and a translation-only file. Paid translation adds a glossary and context translation.
References and next steps
- pypdf official encryption and decryption documentation: https://pypdf.readthedocs.io/en/stable/user/encryption-decryption.html
- pypdf installation guide (AES dependency instructions): see the installation guide section in the pypdf documentation.
🎯 Which approach fits you?
If you have the correct password for a file
Call decrypt() and continue only when the result is 1 or 2.
If the password is wrong or missing
Stop the task and mark it for manual intervention. Do not try to guess the password.
If the file claims to be encrypted but may not be
Log it and have someone review it before deciding whether it is mislabelled.
If you are preparing files for translation
Work through the checklist, keep the originals, and verify the translated output yourself.
❓ FAQ
1. Is is_encrypted enough to know whether I can read a PDF?
No. is_encrypted only shows that the file header declares encryption. You must call decrypt() with the correct password, and the content is accessible only when it returns 1 or 2.
2. What does a return value of 0 from decrypt() mean?
Decryption failed, either because the password was incorrect or because the algorithm is unsupported. Treat the task as unauthorised and do not access .pages.
3. Do I need extra libraries for AES-encrypted PDFs?
Yes. Install cryptography or pycryptodome. Without them, decryption fails outright.
4. Should I skip a file where decrypt("") returns a non-zero value?
No. Log the file and send it for manual review, because automatic skipping may violate compliance policy.
📝 Summary
Check is_encrypted, rely on the return value of decrypt(), and stop any task that is not authorised. Keep originals, log edge cases, and review results manually before you trust them.
Try it now: upload a document and get it translated with the layout intact


