# HTML PDF 변환



HTML 코드를 보내면 화면에 그린 모습 그대로 PDF 파일로 돌려줍니다. 응답은 JSON이 아닌 PDF 파일입니다.



인증: Authorization: Bearer $APICK_API_KEY

본문 있는 REST 요청: multipart/form-data. GET 본문 및 MCP JSON-RPC 규격은 해당 명세를 따릅니다.

인증키는 서버에 보관하세요. 모든 예제는 정적 자료입니다.



## POST /rest/html_to_pdf 응답 필드

## API 요청: POST /rest/html_to_pdf



### 입력

- `html` (string, 필수): 변환할 HTML 코드입니다. 외부 CSS·이미지를 참조하면 변환 결과에서 빠질 수 있으므로 인라인 스타일을 권장합니다.

- `pagination` (integer, 선택): PDF 하단에 페이지 번호를 표시할지 정합니다. 0은 표시하지 않음(기본값), 1은 표시입니다. 숫자 또는 문자열 "0"/"1"로 보낼 수 있습니다.



### 응답 명세

```json

{
  "type": "string",
  "format": "binary"
}

```

### curl

```curl

curl --fail-with-body --request POST 'https://apick.app/rest/html_to_pdf' \
  --header "Authorization: Bearer $APICK_API_KEY" \
  --form-string 'html=<html><head><meta charset="utf-8"></head><body><h1>주문서</h1><p>주문번호 A-1001</p></body></html>' \
  --form-string 'pagination=0' \
  --dump-header response.headers --output result.bin
# response.headers의 Content-Type을 확인한 뒤 파일을 사용하세요.

```

### Node.js (서버 ESM)

```javascript

const form = new FormData();
form.append("html", "<html><head><meta charset=\"utf-8\"></head><body><h1>주문서</h1><p>주문번호 A-1001</p></body></html>");
form.append("pagination", "0");
const response = await fetch("https://apick.app/rest/html_to_pdf", {
  method: "POST",
  headers: { Authorization: "Bearer " + process.env.APICK_API_KEY },
  body: form,
  signal: AbortSignal.timeout(120_000),
});
if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
if ((response.headers.get("content-type") || "").includes("json")) {
  throw new Error(JSON.stringify(await response.json()));
}
const { writeFile } = await import("node:fs/promises");
await writeFile("result.bin", new Uint8Array(await response.arrayBuffer()));

```

### python

```python

import os
import requests
parts = [
    ("html", (None, "<html><head><meta charset=\"utf-8\"></head><body><h1>주문서</h1><p>주문번호 A-1001</p></body></html>")),
    ("pagination", (None, "0")),
]
response = requests.request("POST", "https://apick.app/rest/html_to_pdf",
    headers={"Authorization": "Bearer " + os.environ["APICK_API_KEY"]},
    files=parts,
    timeout=(10, 120), stream=True)
response.raise_for_status()
if "json" in response.headers.get("Content-Type", ""):
    raise RuntimeError(response.json())
with open("result.bin", "wb") as output:
    for chunk in response.iter_content(65536):
        output.write(chunk)

```

### php

```php

<?php
$headers = ["Authorization: Bearer " . getenv("APICK_API_KEY")];
$form = [
    'html' => '<html><head><meta charset="utf-8"></head><body><h1>주문서</h1><p>주문번호 A-1001</p></body></html>',
    'pagination' => '0',
];
$curl = curl_init('https://apick.app/rest/html_to_pdf');
curl_setopt_array($curl, [
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_POSTFIELDS => $form,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_TIMEOUT => 120,
]);
$body = curl_exec($curl);
if ($body === false) { throw new RuntimeException(curl_error($curl)); }
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$type = curl_getinfo($curl, CURLINFO_CONTENT_TYPE) ?: "";
curl_close($curl);
if ($status >= 400) { throw new RuntimeException($body); }
if (strpos($type, "json") !== false) { throw new RuntimeException($body); }
file_put_contents('result.bin', $body);

```

## 사용 예시 1. 주문서 HTML을 PDF로

스타일을 HTML 안에 넣은 템플릿을 그대로 PDF로 만듭니다.

```bash

curl --fail-with-body --request POST 'https://apick.app/rest/html_to_pdf' \
  --header "Authorization: Bearer $APICK_API_KEY" \
  --form-string 'pagination=0' \
  --form-string 'html=<html><head><meta charset="utf-8"><style>h1{font-size:20px}</style></head><body><h1>주문서</h1><p>주문번호 A-1001</p><p>홍길동 님</p></body></html>' \
  --dump-header response.headers --output result.bin
# response.headers의 Content-Type을 확인한 뒤 파일을 사용하세요.

```

- 응답 `Content-Type`이 `application/pdf`이면 `output.pdf`로 저장합니다.

- 한글이 깨지면 `<meta charset="utf-8">`이 들어 있는지 확인하세요.

## 사용 예시 2. 여러 페이지 보고서에 쪽 번호 넣기

페이지를 나눌 위치에 `page-break-after`를 넣고 `pagination=1`로 하단 쪽 번호를 표시합니다.

```bash

curl --fail-with-body --request POST 'https://apick.app/rest/html_to_pdf' \
  --header "Authorization: Bearer $APICK_API_KEY" \
  --form-string 'html=<html><head><meta charset="utf-8"></head><body><h1>1장</h1><div style="page-break-after: always"></div><h1>2장</h1></body></html>' \
  --form-string 'pagination=1' \
  --dump-header response.headers --output result.bin
# response.headers의 Content-Type을 확인한 뒤 파일을 사용하세요.

```

- 각 페이지 하단 가운데에 `현재 / 전체` 형식 번호가 들어갑니다.

## 코드·오류

## 상세 기능·요금

이용 전 확인 주문서·영수증·보고서를 HTML 템플릿으로 만든 뒤 PDF로 내려주거나 메일에 첨부할 때 사용합니다. 스타일은 <style> 태그나 인라인 스타일로 HTML 안에 넣으세요. 상대 경로(./logo.png)로 연결한 이미지·CSS는 불러오지 못하고, 외부 주소로 연결한 리소스도 결과에서 빠질 수 있습니다. 이미지는 data:image/png;base64,… 형식으로 넣으면 안전합니다. 페이지를 나누고 싶은 위치에는 CSS page-break-after: always를 준 빈 블록 요소를 넣으세요. 용지는 A4(21cm × 29.7cm), 여백은 위·아래 1cm, 좌·우 2cm로 고정입니다. pagination=1을 보내면 각 페이지 하단 가운데에 현재 / 전체 형식의 페이지 번호가 들어갑니다. 성공한 건당 30P입니다. 실패·시간 초과 응답은 과금되지 않습니다.

## 상세 요청

항목설정 메서드·주소POST https://apick.app/rest/html_to_pdf 인증 헤더Authorization: Bearer 내 계정의 API 인증키 본문 형식multipart/form-data 요청 예시 form-data 전체 예제 보기

## 상세 응답

성공하면 PDF 본문이 바로 옵니다. 내려받기 파일명은 output.pdf입니다. 응답 헤더 필드타입설명 successinteger1이면 변환에 성공한 것입니다. costinteger이번 요청에서 차감된 포인트입니다. msinteger처리 시간(밀리초)입니다. Content-Typestringapplication/pdf

## 상세 코드·정책

오류와 대처 실패하면 PDF 대신 JSON이 옵니다. HTTP 상태와 Content-Type을 먼저 확인하고, JSON이면 data.error 문구를 기록하세요. 실패 응답의 api.cost는 0입니다. HTTPdata.error대처 400입력 항목이 잘못됐습니다.html에 내용이 있는지 확인하세요. 424알 수 없는 이유로 실패했습니다.HTML을 단순하게 줄여 다시 요청해 보고, 실패를 일으키는 부분을 찾으세요. 408처리 시간 초과로 실패했습니다.data.success가 3입니다. 큰 이미지·긴 표를 줄이거나 문서를 나눠 요청하세요.
