Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

A file-lock error in an iText 7 application is fixed by identifying which path is locked and which process owns it. The usual causes are an iText document that was never closed, a PDF still open in Adobe Reader or another viewer, or an edit that uses the same path for an open input and a destination output. Close every iText resource on every exit path, keep source and destination files separate, and close viewers before replacing a PDF. If the locked path is the image itself, do not assume that every iText 7 image-loading overload keeps or releases a file handle in the same way; verify your exact iText version, overload, image format, operating system and stack trace.

Start with the filename and operation

Read the complete exception, including the filename and the operation that failed. A Windows message such as java.io.FileNotFoundException: Archivio_Etichette_12-4-2015.pdf (Impossibile accedere al file. Il file è utilizzato da un altro processo) means that Windows refused access because another process has the file open. Record whether your code was trying to read, delete, rename or overwrite the path.

  • Image input: the path passed to ImageDataFactory.create(...).
  • Source PDF: the file opened by PdfReader when you modify an existing document.
  • Destination PDF: the path supplied to PdfWriter, often the file left open in a viewer.

That classification determines the remedy. A viewer lock is handled outside Java; an iText lifecycle problem is handled by closing the document and its associated resources; an image-specific lifetime question requires version-specific verification.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Close the iText document lifecycle

The official iText 7 image example creates image data from a path, adds an Image to a Document, and calls document.close() after all content has been added. Use the same lifecycle in production, and ensure closing occurs when generation fails as well as when it succeeds.

Minimal image-to-PDF pattern

String imagePath = "input/logo.png";
String outputPath = "output/result.pdf";

PdfWriter writer = new PdfWriter(outputPath);
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf);

Image image = new Image(ImageDataFactory.create(imagePath));
document.add(image);

// Run this after the final element has been added.
document.close();

Do not leave the Document, PdfDocument or writer open while a later step tries to rename, delete or overwrite the destination. PdfDocument has close behavior and an isClosed() state; the exact reader/writer closure semantics should be checked against the iText version used by your application.

Make closure exception-safe

The tutorial examples show normal completion. Your application should also close resources when an image is corrupt, a page cannot be written, or another exception interrupts composition. A practical structure is to create the document, put composition in a try block, and close it from finally if it is not already closed.

Document document = null;
try {
    PdfWriter writer = new PdfWriter(outputPath);
    PdfDocument pdf = new PdfDocument(writer);
    document = new Document(pdf);
    document.add(new Image(ImageDataFactory.create(imagePath)));
} finally {
    if (document != null && !document.getPdfDocument().isClosed()) {
        document.close();
    }
}

Adapt this pattern to the constructors and close semantics of your installed iText release. If your project uses a higher-level helper, inspect whether it owns the PdfDocument and whether closing the wrapper closes the underlying writer.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When editing an existing PDF, separate input and output

For an existing PDF, the documented structure uses a PdfReader for the source and a separate PdfWriter for the destination. The resulting PdfDocument is wrapped by Document, which is closed after the image is added.

PdfReader reader = new PdfReader("input/source.pdf");
PdfWriter writer = new PdfWriter("output/with-image.pdf");
PdfDocument pdfDoc = new PdfDocument(reader, writer);
Document document = new Document(pdfDoc);

Image image = new Image(ImageDataFactory.create("input/stamp.png"));
document.add(image);
document.close();

Do not point the writer at the same pathname as an input reader that is still open unless the exact workflow is supported by your iText version and operating system. A separate destination also gives you a safe rollback: if generation fails, the original source remains intact. Once the new file is validated, replace the old file in a separate, controlled step.

If the output PDF is locked by a viewer

On Windows, Adobe Reader, Acrobat and other viewers can hold an open PDF. Windows then refuses a rename or rewrite even though your Java code is correct. Close the document in every viewer window before rerunning the job. Also check preview panes, indexing or synchronization software, and a second Java process that may still own the file.

Use a new destination during development

When repeated runs collide with an open or recently generated file, write each run to a unique name, such as result-20260929-143015.pdf. A timestamped destination avoids overwriting a file that somebody is inspecting and is the practical workaround described for iterative Windows workflows. It does not replace proper resource closure; old files still need a retention or cleanup policy.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If the image path itself is reported

The iText tutorial confirms path-based loading with ImageDataFactory.create(path), but the available documentation does not establish one universal rule for how long every iText 7 version and image format keeps an underlying image-file handle. Do not claim that closing the image object, or closing the PDF, always releases the source image immediately.

  1. Capture the exact iText 7 version, Java version, operating system, image format and complete stack trace.
  2. Reduce the case to one image and one output file. Test a copy of the image under a different name.
  3. Confirm whether the failure occurs while reading the image, or later while deleting or replacing it.
  4. Check the API and source documentation for that exact release and overload, or ask iText support, before applying a version-independent workaround.

If writing to a new output succeeds but deleting the source image fails, the owner may be your own application or another process rather than the PDF writer. Process-monitoring tools on the affected operating system can identify the handle owner; use their findings instead of guessing.

Diagnostic decision table

Locked path Likely owner First fix Safe fallback
Destination PDF Viewer or another process Close the viewer and stop competing jobs Write a new timestamped destination
Source PDF Open reader, viewer or another process Close external programs; close the iText document Copy the source to a working file
Image input Uncertain; depends on version, overload and format Reproduce with exact version and stack trace Use a controlled copy while investigating
Delete/rename after success Your still-open writer/document or viewer Close resources before filesystem operations Perform replacement in a later process step
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common failure modes

“I called close, but the file is still locked”

Verify that the call is reached on both success and failure paths, that you close the top-level Document, and that no second PdfDocument or reader remains open. Log the destination path and isClosed() state immediately before filesystem operations.

“The exception names a PDF I did not just create”

You may be opening that file as a source while another run, viewer or service owns it. Trace every reader and writer path, and ensure concurrent jobs do not share a destination name.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

“Changing the image format fixed it”

That is a useful observation, not proof of a general iText rule. Preserve the smallest reproduction and report the exact format and overload; behavior may differ between releases.

“A retry makes the problem disappear”

A retry can merely outwait a viewer or another process. Add deterministic closure and ownership checks instead of relying on timing. If retries are necessary for an external process, use bounded backoff and report the owning process.

Or skip the browser setup:

If your actual goal is obtaining clean website screenshots for a PDF or document pipeline, ScreenshotNeo provides a single HTTP call rather than a browser you must install and manage. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups and chat widgets; each step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server exposes take_screenshot, get_page_info and capture_pdf to Claude, Cursor and other MCP clients.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for authentication, output formats and options. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Python and Node.js equivalents

Python

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)

Node.js

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', data));

Operational checklist

  • Log the exact locked filename and filesystem operation.
  • Use distinct source and destination paths for PDF edits.
  • Close Document on success and failure.
  • Close PDF viewers before replacing output files.
  • Prevent concurrent jobs from sharing a destination name.
  • For image-source locks, record exact version, overload, format and stack trace before escalating.

Frequently Asked Questions

Does renaming the image solve an iText 7 lock?

It can distinguish a path collision from a persistent handle, but it does not identify the owner. Use it only as a controlled reproduction step and then inspect the exact process and iText version.

Can I safely overwrite the source PDF while reading it?

Use a separate destination unless your specific iText version documents an in-place workflow. Separate paths avoid truncating or locking the file being read.

Why is a lock intermittent on Windows?

Intermittence usually indicates timing with a viewer, another job, indexing software or an exception path that sometimes skips closure; it is not evidence that the lock is harmless.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.