Created
March 26, 2024 11:46
-
-
Save geobabbler/151c3d226f1a5db242750c0a5b94286a to your computer and use it in GitHub Desktop.
Simple script to dump Wordpress posts to individual PDF files.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pdfkit | |
import requests | |
''' | |
The current theme will be applied to outputs, so it is recommended to switch to a simple theme before exporting. | |
''' | |
#Generate PDF from individual post URL | |
def url_to_pdf(url, output_filename): | |
try: | |
# Fetch HTML content from the URL | |
response = requests.get(url) | |
response.raise_for_status() # Raises an HTTPError if the response was an unsuccessful status code | |
# Convert HTML to PDF and save it | |
pdfkit.from_string(response.text, output_filename) | |
print(f"PDF successfully saved as {output_filename}") | |
except requests.exceptions.RequestException as e: | |
#print(f"Error fetching the URL: {e}") | |
pass | |
except Exception as e: | |
#print(f"Error converting HTML to PDF: {e}") | |
pass | |
#Get all post URLs via Wordpress API | |
def list_all_posts(website_url): | |
posts_list = [] | |
api_url = f"{website_url}/wp-json/wp/v2/posts" | |
page = 1 | |
while True: | |
# Fetch a page of posts | |
response = requests.get(api_url, params={'per_page': 100, 'page': page}) | |
# If the response status code is not 200, break the loop | |
if response.status_code != 200: | |
#print(f"Finished or encountered an error. HTTP status code: {response.status_code}") | |
break | |
posts = response.json() | |
# If the page is empty, break the loop | |
if not posts: | |
break | |
# Print URLs and titles of posts | |
for post in posts: | |
posts_list.append(post['link']) | |
#print(post['link']) | |
page += 1 | |
return posts_list | |
# Usage | |
website_url = "https://blog.yoursite.org" | |
pl = list_all_posts(website_url) | |
#use an integer to generate unique file names. | |
ord = 0 | |
for p in pl: | |
outfile = "p" + str(ord) + ".pdf" | |
url_to_pdf(p, outfile) | |
ord += 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment