API 참조
이 문서는 Markdown to PDF 변환기의 내부 API 및 연동 가능성에 대한 기술적 세부 정보를 제공합니다.
개요
The Markdown to PDF converter is built using modern web technologies and provides a robust API for document processing and PDF generation.
핵심 기술
프론트엔드 프레임워크
- Vue.js 3: Reactive frontend framework
- TypeScript: Type-safe development
- Composition API: Modern Vue.js patterns
PDF 생성
- marked.js: Markdown parsing and rendering
스타일 및 UI
- TailwindCSS: Utility-first CSS framework
- Lucide Icons: Modern icon library
- Vue Sonner: Toast notifications
내부 API 구조
Markdown 처리
parseMarkdown(content: string): string
Markdown 콘텐츠를 HTML로 변환합니다.
매개변수:
content(string): Raw Markdown 콘텐츠
반환값:
string: Rendered HTML
예:
const html = parseMarkdown("# Hello World\nThis is **bold** text.");
// Returns: '<h1>Hello World</h1>\n<p>This is <strong>bold</strong> text.</p>'
validateMarkdown(content: string): boolean
Markdown 콘텐츠의 잠재적 문제를 검증합니다.
매개변수:
content(string): Markdown 콘텐츠 to validate
반환값:
boolean: True if content is valid
예:
const isValid = validateMarkdown("# Valid Header\nValid content.");
// Returns: true
PDF 생성
generatePDF(options: PDFOptions): Promise<Blob>
HTML 콘텐츠에서 PDF를 생성합니다.
매개변수:
options(PDFOptions): PDF 생성 옵션
PDFOptions Interface:
interface PDFOptions {
content: string; // HTML content
pageSize: "A4" | "A3" | "Letter" | "Legal";
orientation: "portrait" | "landscape";
marginTop: number; // in mm
marginBottom: number; // in mm
marginLeft: number; // in mm
marginRight: number; // in mm
includeToc: boolean;
includePageNumbers: boolean;
}
반환값:
Promise<Blob>: Blob으로 생성된 PDF
예:
const options = {
content: "<h1>Document</h1><p>Content</p>",
pageSize: "A4",
orientation: "portrait",
marginTop: 20,
marginBottom: 20,
marginLeft: 20,
marginRight: 20,
includeToc: true,
includePageNumbers: true,
};
const pdfBlob = await generatePDF(options);
downloadPDF(blob: Blob, filename?: string): void
PDF Blob을 파일로 다운로드합니다.
매개변수:
blob(Blob): 다운로드할 PDF Blobfilename(string, optional): 사용자 지정 파일명
예:
downloadPDF(pdfBlob, "my-document.pdf");
기록 관리
saveToHistory(record: HistoryRecord): void
변환 기록을 기록에 저장합니다.
HistoryRecord Interface:
interface HistoryRecord {
id: string;
title: string;
content: string;
contentLength: number;
pdfOptions: PDFOptions;
timestamp: number;
}
예:
const record = {
id: Date.now().toString(),
title: "My Document",
content: "# My Document\nContent here...",
contentLength: 25,
pdfOptions: options,
timestamp: Date.now(),
};
saveToHistory(record);
loadFromHistory(id: string): HistoryRecord | null
ID로 기록 항목을 불러옵니다.
매개변수:
id(string): 기록 항목 ID
반환값:
HistoryRecord | null: 기록 항목 또는 찾을 수 없으면 null
clearHistory(): void
모든 기록 항목을 지웁니다.
deleteHistoryRecord(id: string): void
특정 기록 항목을 삭제합니다.
매개변수:
id(string): 삭제할 기록 항목 ID
컴포넌트 API
MarkdownToPDF 컴포넌트
Props
interface Props {
id: string; // 컴포넌트 ID
docHref?: string; // 문서 링크
class?: string; // CSS 클래스
}
Events
interface Events {
"pdf-generated": (blob: Blob) => void;
"history-saved": (record: HistoryRecord) => void;
error: (error: Error) => void;
}
Methods
interface Methods {
generatePDF(): Promise<void>;
clearContent(): void;
loadExample(): void;
downloadPDF(): void;
}
반응형 데이터
markdownContent: Ref<string>
현재 Markdown 콘텐츠에 대한 반응형 참조.
renderedHtml: Ref<string>
렌더링된 HTML에 대한 반응형 참조.
pdfOptions: Ref<PDFOptions>
PDF 생성 옵션에 대한 반응형 참조.
isGenerating: Ref<boolean>
PDF 생성 상태에 대한 반응형 참조.
pdfBlob: Ref<Blob | null>
생성된 PDF Blob에 대한 반응형 참조.
유틸리티 함수
콘텐츠 처리
extractTitle(content: string): string
Markdown 콘텐츠에서 첫 번째 제목을 문서 제목으로 추출합니다.
매개변수:
content(string): Markdown 콘텐츠
반환값:
string: 추출된 제목 또는 기본 제목
예:
const title = extractTitle("# My Document\nContent...");
// Returns: 'My Document'
formatDate(timestamp: number): string
타임스탬프를 읽기 쉬운 날짜 문자열로 형식 지정합니다.
매개변수:
timestamp(number): Unix 타임스탬프
반환값:
string: 형식 지정된 날짜 문자열
예:
const date = formatDate(Date.now());
// Returns: '2024-01-15 14:30:25'
검증 함수
validatePDFOptions(options: PDFOptions): boolean
PDF 생성 옵션을 검증합니다.
매개변수:
options(PDFOptions): 검증할 옵션
반환값:
boolean: 옵션이 유효하면 true
sanitizeContent(content: string): string
XSS 공격을 방지하기 위해 콘텐츠를 소독합니다.
매개변수:
content(string): 소독할 콘텐츠
반환값:
string: 소독된 콘텐츠
오류 처리
오류 유형
PDFGenerationError
PDF 생성이 실패하면 발생합니다.
class PDFGenerationError extends Error {
constructor(message: string, cause?: Error) {
super(message);
this.name = "PDFGenerationError";
this.cause = cause;
}
}
ValidationError
콘텐츠 검증이 실패하면 발생합니다.
class ValidationError extends Error {
constructor(message: string, field?: string) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
오류 처리 패턴
try {
const pdfBlob = await generatePDF(options);
downloadPDF(pdfBlob);
} catch (error) {
if (error instanceof PDFGenerationError) {
console.error("PDF generation failed:", error.message);
// Handle PDF generation error
} else if (error instanceof ValidationError) {
console.error("Validation failed:", error.message);
// Handle validation error
} else {
console.error("Unexpected error:", error);
// Handle unexpected error
}
}
성능 고려 사항
메모리 관리
- Blob Cleanup: PDF Blob은 자동으로 정리됩니다
- DOM Cleanup: 임시 DOM 요소가 제거됩니다
- Event Listeners: 이벤트 리스너가 적절히 정리됩니다
최적화 전략
- Lazy Loading: 리소스는 필요할 때만 로드됩니다
- Debouncing: 과도한 처리를 방지하기 위해 입력 변경이 디바운스됩니다
- Caching: 성능을 위해 렌더링된 콘텐츠가 캐시됩니다
- Background Processing: PDF 생성은 백그라운드에서 수행됩니다
브라우저 호환성
지원 브라우저
- Chrome: 80+
- Firefox: 75+
- Safari: 13+
- Edge: 80+
기능 감지
// Check for required features
const hasRequiredFeatures = () => {
return (
"Blob" in window &&
"URL" in window &&
"createObjectURL" in URL &&
"download" in document.createElement("a")
);
};
연동 예
기본 연동
import { generatePDF, downloadPDF } from "@/utils/pdf-generator";
const convertMarkdownToPDF = async (markdownContent, options) => {
try {
const html = parseMarkdown(markdownContent);
const pdfBlob = await generatePDF({ ...options, content: html });
downloadPDF(pdfBlob, "document.pdf");
} catch (error) {
console.error("Conversion failed:", error);
}
};
기록이 포함된 고급 연동
import { generatePDF, saveToHistory, loadFromHistory } from "@/utils/pdf-generator";
const convertWithHistory = async (content, options) => {
const record = {
id: Date.now().toString(),
title: extractTitle(content),
content,
contentLength: content.length,
pdfOptions: options,
timestamp: Date.now(),
};
const pdfBlob = await generatePDF({ ...options, content });
saveToHistory(record);
return pdfBlob;
};
향후 API 개선
계획된 기능
- Batch Processing: 여러 문서 변환
- Template System: 사전 정의된 서식 템플릿
- Custom Fonts: 사용자 지정 글꼴 임베딩 지원
- Watermarks: 생성된 PDF에 워터마크 추가
- Digital Signatures: 디지털 서명 지원 추가
API 버전 관리
향후 API 버전은 새 기능을 추가하면서 하위 호환성을 유지합니다. 버전 정보는 API를 통해 제공됩니다.
더 많은 예와 고급 사용법은 사용 예 문서를 참조하세요.