Skip to content

Commit

Permalink
Reinstate json endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
mbenedettini committed Sep 23, 2024
1 parent 550b897 commit f5b1edf
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 1 deletion.
50 changes: 50 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
```bash
#!/bin/bash

# HTML content to be converted (escaped for JSON)
HTML_CONTENT="<html><body><h1>Test PDF</h1><p>This is a test PDF generated from HTML.</p></body></html>"

# Create a temporary file for the form data
TEMP_FILE=$(mktemp)

# Write the HTML content to the temporary file
echo -n "$HTML_CONTENT" > "$TEMP_FILE"

# Send POST request and save the response as test.pdf
curl -v -X POST \
-H "Authorization: 1234567890" \
-H "Content-Type: multipart/form-data" \
-F "html=@$TEMP_FILE" \
--output test.pdf \
http://localhost:8080/html2pdf

# Remove the temporary file
rm "$TEMP_FILE"

echo "PDF saved as test.pdf"
```

```bash
#!/bin/bash

# Define the URL of the endpoint
URL="http://localhost:8080/html2pdf:json"

# Define the JSON data to be sent
JSON_DATA='{
"value": "<html><body><h1>Hello, World!</h1></body></html>"
}'

# Send a POST request with the JSON data
curl -X POST $URL \
-H "Content-Type: application/json" \
-d "$JSON_DATA" \
-o output.pdf

# Check if the request was successful
if [ $? -eq 0 ]; then
echo "PDF saved to output.pdf"
else
echo "Failed to generate PDF"
fi
```
16 changes: 15 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { oak } from "./deps.ts";
import { oak, BodyType } from "./deps.ts";
import { html2pdf } from "./puppeteer.ts";

const app = new oak.Application();
Expand All @@ -10,6 +10,7 @@ router.get("/", (ctx: oak.Context) => {
};
});


router.post("/html2pdf", async (ctx: oak.Context) => {
if (!ctx.request.hasBody) {
return;
Expand All @@ -28,6 +29,19 @@ router.post("/html2pdf", async (ctx: oak.Context) => {
ctx.response.type = 'application/pdf';
});

router.post("/html2pdf:json", async (ctx: oak.Context) => {
const body = ctx.request.body;

if (body.type() !== "json") {
return;
}
const value = await body.json();
const html = value.value as string;
const pdf = await html2pdf(html);
ctx.response.body = pdf;
ctx.response.type = 'application/pdf';
});

app.use(router.routes());
app.use(router.allowedMethods());

Expand Down

0 comments on commit f5b1edf

Please sign in to comment.