Untitled conversation
- User
from pathlib import Path from PyPDF2 import PdfMerger import os import logging from weasyprint import HTML, CSS logger = logging.getLogger(__name__) def write_pdf_weasy(html_path, pdf_path): # Read HTML content with open(html_path, encoding='utf-8') as f: html_content = f.read() # Define CSS for two-column layout and pagination css = CSS(string=""" @page { size: A4 landscape; margin: 20px; } body { font-size: 7pt; font-family: sans-serif; column-count: 2; column-gap: 20px; margin: 0; padding: 20px; } p, h1, h2, h3, blockquote { break-inside: avoid; page-break-inside: avoid; } h1 { font-size: 16pt; } figure img { max-width: 100%; max-height: 200px; height: auto; display: block; margin: 0 auto; } figure { break-inside: avoid; margin: 1em 0; } """) # Generate PDF HTML(string=html_content).write_pdf(pdf_path, stylesheets=[css]) def merge_pdfs(pdf_files, output_path): """Merge multiple PDF files into one""" merger = PdfMerger() for pdf in pdf_files: merger.append(str(pdf)) merger.write(output_path) logger.debug("Wrote combined PDF", extra={"output_path": output_path}) merger.close() return output_path async def _combine(directory: Path, pattern: str = "*.html"): html_files = list(directory.glob(pattern)) pdf_files = [html.with_name(html.stem + ".pdf") for html in html_files] for html, pdf in zip(html_files, pdf_files): write_pdf_weasy(str(html), pdf) # Remember that the parent's name is the feed id # and the child is the datetime of its latest entry # Remember that we assume the directory name is the feed id outfile_name = f"{directory.parent.name}_{directory.name}_combined.pdf" # Join the outfile_name with the directory outfile_path = directory / outfile_name merge_pdfs(pdf_files, outfile_path) for pdf in pdf_files: try: os.remove(pdf) logger.debug("Deleted pdf", extra={"filepath": pdf}) except Exception: logger.error("Failed to delete pdf", extra={"filepath": pdf}, exc_info=True)Currently this converts each article to PDF with a two-column layout and then concatenates the PDFs. How might we instead concatenate so that articles can flow smoothly? For example one article might finish in a left column and another start in the right column.
Assistant
To achieve a continuous flow between articles where one can end in the left column and the next begin in the right column, you'll need to modify the approach to combine all HTML content first, then convert it to a single PDF. Here's how you could modify the code:
from pathlib import Path from weasyprint import HTML, CSS import logging logger = logging.getLogger(__name__) def combine_html_contents(html_files): """Combine multiple HTML files into a single HTML string""" combined_content = [] for html_file in html_files: with open(html_file, encoding='utf-8') as f: content = f.read() # Extract the body content (you might need to adjust this based on your HTML structure) body_start = content.find('<body') body_start = content.find('>', body_start) + 1 body_end = content.find('</body>') if body_start > 0 and body_end > 0: content = content[body_start:body_end] combined_content.append(content) # Wrap in a basic HTML structure return f""" <!DOCTYPE html> <html> <head><meta charset="utf-8"></head> <body> {'\n'.join(combined_content)} </body> </html> """ async def _combine(directory: Path, pattern: str = "*.html"): html_files = list(directory.glob(pattern)) # Combine all HTML content combined_html = combine_html_contents(html_files) # Define CSS for two-column layout and pagination css = CSS(string=""" @page { size: A4 landscape; margin: 20px; } body { font-size: 7pt; font-family: sans-serif; column-count: 2; column-gap: 20px; margin: 0; padding: 20px; } p, h1, h2, h3, blockquote { break-inside: avoid; page-break-inside: avoid; } h1 { font-size: 16pt; } figure img { max-width: 100%; max-height: 200px; height: auto; display: block; margin: 0 auto; } figure { break-inside: avoid; margin: 1em 0; } /* Add a separator between articles */ .article-separator { border-top: 1px solid #ccc; margin: 1em 0; break-inside: avoid; } """) # Create output filename outfile_name = f"{directory.parent.name}_{directory.name}_combined.pdf" outfile_path = directory / outfile_name # Generate single PDF HTML(string=combined_html).write_pdf( str(outfile_path), stylesheets=[css] ) logger.debug("Created combined PDF", extra={"output_path": outfile_path})Key changes made:
- Removed the PDF merging step since we're now creating a single PDF
- Added a function to combine HTML content from multiple files
- Process the combined HTML content in one go with WeasyPrint
- Added CSS for article separation (optional)
This approach will allow text to flow naturally between columns and pages. Articles can now end in the left column and the next article can start in the right column.
A few considerations:
- You might want to add some visual separation between articles (the CSS includes an optional article-separator class)
- The HTML combining function assumes a simple structure - you might need to adjust it based on your actual HTML structure
- You might want to add additional CSS to control how articles break across pages
- If your HTML files have different CSS styles, you'll need to handle merging those styles as well
You could also add a divider between articles in the HTML combination step:
combined_content.append(content) if i < len(html_files) - 1: # Don't add after the last article combined_content.append('<div class="article-separator"></div>')This will give you better control over the visual flow between articles while maintaining the continuous column layout.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.