Generowanie PDF z tekstu (TXT → PDF)
Podstawowa konwersja pliku tekstowego do PDF:
Python1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29from reportlab.lib.pagesizes import letter from reportlab.pdfgen import canvas from pathlib import Path def txt_to_pdf(input_txt: str, output_pdf: str): """Konwertuje plik tekstowy do PDF.""" c = canvas.Canvas(output_pdf, pagesize=letter) width, height = letter # Czytanie pliku tekstowego with open(input_txt, 'r', encoding='utf-8') as f: text = f.read() # Dzielenie tekstu na linie lines = text.split('\n') y = height - 50 for line in lines: if y < 50:# Nowa strona c.showPage() y = height - 50 c.drawString(50, y, line) y -= 15 c.save() print(f"Konwertowano {input_txt} do {output_pdf}") txt_to_pdf("dokument.txt", "dokument.pdf")
Generowanie PDF z CSV (CSV → PDF)
Konwersja danych CSV do tabeli PDF:
Python1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36from reportlab.lib.pagesizes import letter from reportlab.lib import colors from reportlab.platypus import SimpleDocTemplate, Table, TableStyle import csv def csv_to_pdf(input_csv: str, output_pdf: str): """Konwertuje plik CSV do PDF z tabelą.""" doc = SimpleDocTemplate(output_pdf, pagesize=letter) elements = [] data = [] with open(input_csv, 'r', encoding='utf-8') as f: reader = csv.reader(f) for row in reader: data.append(row) table = Table(data) table.setStyle(TableStyle([ ('BACKGROUND', (0, 0), (-1, 0), colors.grey), ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'), ('FONTSIZE', (0, 0), (-1, 0), 14), ('BOTTOMPADDING', (0, 0), (-1, 0), 12), ('BACKGROUND', (0, 1), (-1, -1), colors.beige), ('GRID', (0, 0), (-1, -1), 1, colors.black) ])) elements.append(table) doc.build(elements) print(f"Konwertowano {input_csv} do {output_pdf}") csv_to_pdf("dane.csv", "raport.pdf")
Konwersja obrazów do PDF (IMG → PDF)
Łączenie wielu obrazów w jeden PDF lub konwersja pojedynczego obrazu:
Python1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31from PIL import Image from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter from pathlib import Path def images_to_pdf(image_files: list[str], output_pdf: str): """Konwertuje obrazy do jednego pliku PDF.""" c = canvas.Canvas(output_pdf, pagesize=letter) width, height = letter for img_path in image_files: img = Image.open(img_path) img_width, img_height = img.size ratio = min(width / img_width, height / img_height) * 0.9 new_width = img_width * ratio new_height = img_height * ratio x = (width - new_width) / 2 y = (height - new_height) / 2 c.drawImage(img_path, x, y, width=new_width, height=new_height) c.showPage() c.save() print(f"Konwertowano {len(image_files)} obrazów do {output_pdf}") images_to_pdf(["obraz1.png", "obraz2.jpg", "obraz3.png"], "obrazy.pdf")
Ekstrakcja tekstu z PDF (PDF → TXT)
Wyodrębnianie tekstu z dokumentów PDF:
Python1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17from pypdf import PdfReader def pdf_to_txt(input_pdf: str, output_txt: str): """Ekstrahuje tekst z pliku PDF.""" reader = PdfReader(input_pdf) text_content = [] for page_num, page in enumerate(reader.pages, 1): text = page.extract_text() text_content.append(f"=== Strona {page_num} ===\n{text}\n") with open(output_txt, 'w', encoding='utf-8') as f: f.write('\n'.join(text_content)) print(f"Ekstrahowano tekst z {input_pdf} do {output_txt}") pdf_to_txt("dokument.pdf", "dokument.txt")
Zaawansowana ekstrakcja z pdfminer
Dla bardziej skomplikowanych PDF-ów lepiej użyć pdfminer.six:
Python1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21from pdfminer.high_level import extract_text from pdfminer.layout import LAParams def advanced_pdf_to_txt(input_pdf: str, output_txt: str): """Zaawansowana ekstrakcja tekstu z PDF.""" # Ekstrakcja z lepszą konfiguracją layoutu text = extract_text( input_pdf, laparams=LAParams( line_margin=0.5, word_margin=0.1, char_margin=2.0 ) ) with open(output_txt, 'w', encoding='utf-8') as f: f.write(text) print(f"Ekstrahowano tekst z {input_pdf} do {output_txt}") advanced_pdf_to_txt("zlozony_dokument.pdf", "tekst.txt")
Batch konwersja wielu plików
Automatyzacja konwersji wielu plików naraz:
Python1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22from pathlib import Path from pypdf import PdfReader def batch_pdf_to_txt(directory: str, output_dir: str = None): """Konwertuje wszystkie PDF-y w katalogu do TXT.""" pdf_dir = Path(directory) if output_dir: out_dir = Path(output_dir) out_dir.mkdir(parents=True, exist_ok=True) else: out_dir = pdf_dir pdf_files = list(pdf_dir.glob("*.pdf")) for pdf_file in pdf_files: output_file = out_dir / f"{pdf_file.stem}.txt" pdf_to_txt(str(pdf_file), str(output_file)) print(f"Przetworzono {len(pdf_files)} plików PDF") batch_pdf_to_txt("./dokumenty/", "./teksty/")
Konwersja HTML do PDF
Generowanie PDF z HTML:
Python1 2 3 4 5 6 7 8from weasyprint import HTML def html_to_pdf(input_html: str, output_pdf: str): """Konwertuje plik HTML do PDF.""" HTML(filename=input_html).write_pdf(output_pdf) print(f"Konwertowano {input_html} do {output_pdf}") html_to_pdf("raport.html", "raport.pdf")
Podsumowanie
Python oferuje narzędzia do konwersji w obie strony:
- Do PDF: TXT → PDF, CSV → PDF, IMG → PDF, HTML → PDF
- Z PDF: PDF → TXT z ekstrakcją tekstu
- Batch processing: automatyczna konwersja wielu plików
Te techniki są kluczowe w automatyzacji przetwarzania dokumentów.
➡️ Następny artykuł
Po opanowaniu konwersji plików, naucz się tworzyć profesjonalne spisy treści w PDF:
Tworzenie spisu treści i łączenie rozdziałów w PDF — dodawanie zakładek, hierarchicznych struktur nawigacyjnych i automatyczne generowanie spisów treści w dużych dokumentach.



