From da8491c164ecd3dd3a7fb9ae6e277ab7fec86559 Mon Sep 17 00:00:00 2001 From: tke Date: Fri, 16 Feb 2024 10:52:13 +0100 Subject: [PATCH] Added convert2pdf.sh --- codegrab/convert2pdf.sh | 59 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100755 codegrab/convert2pdf.sh diff --git a/codegrab/convert2pdf.sh b/codegrab/convert2pdf.sh new file mode 100755 index 0000000..70d7312 --- /dev/null +++ b/codegrab/convert2pdf.sh @@ -0,0 +1,59 @@ +#!/bin/bash + +# Check if a file argument is provided +if [ "$#" -ne 1 ]; then + echo "Usage: $0 " + exit 1 +fi + +# Assign the file argument to a variable +FILE_TO_CONVERT=$1 +FILE_NAME=$(basename "$FILE_TO_CONVERT") + +# Define the Gotenberg Docker image +GOTENBERG_IMAGE="gotenberg/gotenberg:8" + +# Start the Gotenberg Docker container in the background +docker run --rm -d -p 3000:3000 --name gotenberg $GOTENBERG_IMAGE + +# Function to stop the Docker container +function stop_container { + docker stop gotenberg +} + +# Register the stop_container function to be called on script exit +trap stop_container EXIT + +# Wait for a moment to ensure that the container is up and running +sleep 3 + +# Determine the correct API endpoint based on the file extension +EXTENSION="${FILE_TO_CONVERT##*.}" +API_ENDPOINT="/forms/libreoffice/convert" + +# Special handling for HTML files to use Chromium conversion +if [ "$EXTENSION" == "html" ]; then + API_ENDPOINT="/forms/chromium/convert/html" + # Ensure the HTML file is named index.html + if [ "$FILE_NAME" != "index.html" ]; then + echo "Renaming $FILE_NAME to index.html for conversion" + cp "$FILE_TO_CONVERT" "/tmp/index.html" + FILE_TO_CONVERT="/tmp/index.html" + fi +fi + +# Convert the file to PDF using the Gotenberg API +curl --request POST \ + --url http://localhost:3000$API_ENDPOINT \ + --header 'Content-Type: multipart/form-data' \ + --form files=@"$FILE_TO_CONVERT" \ + -o converted.pdf + +# Check if the conversion was successful +if [ ! -f converted.pdf ]; then + echo "Failed to convert the file to PDF." + exit 3 +fi + +# Display the PDF with Evince +evince converted.pdf &