Forum Discussion

n421m's avatar
n421m
Copper Contributor
May 02, 2025

Indentation is lost when copying Python code from PDF/Word back into Jupyter Notebook

Hello everyone,

I’m working on a thesis project using JupyterLab where I wrote a series of Python scripts. I copied those scripts into a Word document for formatting (e.g., to include in the appendix), and then exported the Word file to PDF. Visually, everything looks fine in both Word and PDF.

However, when I try to copy the code back from the PDF (or even from Word) into a Jupyter Notebook cell, the indentation is completely lost. All lines are aligned to the left, which obviously causes syntax errors in Python, especially in function definitions and loops.

You can see the issue in the attached image:
- On the left side (PDF), I can't even select the indentation — only the characters.
- On the right side (Word), I can select the whitespace, but copying it still results in broken indentation in Jupyter.

What I’ve tried so far:
- Using monospace fonts like Courier New and Consolas in Word.
- Setting line spacing and paragraph spacing to exactly 0pt before/after.
- Exporting the Word file as PDF instead of printing.
- Tried using “preformatted” or code styles where possible.

My goal:
I want to include code samples in my thesis (Word/PDF), but also ensure that anyone copying them back into Jupyter Notebook or a `.py` file will retain correct indentation without having to fix it manually.

Has anyone found a reliable workflow or formatting technique that preserves indentation across these formats?

Thanks in advance for any help or ideas!

 

1 Reply

  • To ensure proper indentation is maintained when copying code, consider utilizing Word’s built-in "Code" style or structuring the code within a single-column table. This approach enhances formatting consistency and helps preserve indentation during the transfer process.

Resources