코어 API

코어 API

이 가이드는 Document 및 Page 클래스를 사용하여 PDF 문서를 열고, 편집하고, 조립하고, 저장하는 방법을 보여줍니다 — TypeScript용 Aspose.PDF FOSS에서 모든 작업의 진입점입니다. Document는 전체 PDF 파일을 로드하고, 생성하고, 조립하고, 저장합니다; Page는 doc.Pages를 통해 접근할 수 있으며 페이지별 텍스트, 이미지, 주석 및 콘텐츠 스트림 작업을 제공합니다.


문서 수명 주기

Document.OpenFile()은 파일 경로에서 PDF를 엽니다; Document.Open()은 메모리 내 Uint8Array를 받아들입니다. 페이지를 현장에서 검사하고 편집할 수 있으며, Document.WriteTo()은 결과를 다시 기록합니다 — 선택적으로 xref-stream 및 object-stream 압축을 사용할 수 있습니다.

import { Document } from '@asposefoss/pdf';

// Open from disk (or Document.Open(uint8array) for in-memory data)
const doc = Document.OpenFile('input.pdf');

// Inspect and edit pages
const pages = doc.Pages;
console.log(pages.length);
pages[0].Rotate = 90;
doc.RemovePage(2);                 // 1-based page number
doc.Reorder([3, 1, 2]);

// Metadata
doc.SetMetadata({ title: 'Report', author: 'Jane', custom: { Dept: 'R&D' } });

// Save
doc.WriteTo('output.pdf');         // or: const bytes = doc.Save();
doc.WriteTo('small.pdf', { compressed: true }); // xref stream + object streams

페이지 분할, 병합 및 추출

Document.Split()은 페이지당 하나의 Document을 반환합니다. Document.ExtractPages()는 1부터 시작하고 중복 허용되는 페이지 목록을 받아 해당 페이지들만 포함한 새로운 Document을 반환합니다. Document.Append()와 Document.InsertPage()는 문서 간에 페이지를 복사하고, Document.Merge()은 여러 문서를 하나로 결합합니다.

const parts = doc.Split();                       // one Document per page
const chapter = doc.ExtractPages([3, 4, 5]);     // subset (1-based, repeats allowed) as a new Document

docA.Append(docB);                               // copy all of docB's pages onto docA
docA.InsertPage(1, docB.Pages[0]);               // copy a single page across documents

새 문서 만들기

Document.New()은 지정된 PageFormat에서 빈 문서를 시작합니다. Page.AddText()는 위치 지정된 텍스트를 배치하고, Document.AddPage()은 PageFormat.A4.landscape()와 같은 회전 형식을 포함한 추가 페이지를 추가합니다.

import { Document, PageFormat } from '@asposefoss/pdf';
const doc = Document.New(PageFormat.A4);          // one blank A4 page
doc.Pages[0].AddText('Hello', 72, 720, { fontSize: 14 });
doc.AddPage(PageFormat.A4.landscape());           // append more as you go
doc.WriteTo('scratch.pdf');

워터마크와 페이지 번호

Page.AddText()는 회전, 색상 및 불투명성을 지원하므로 추가 클래스 없이 페이지 번호와 대각선 워터마크를 렌더링하기에 충분합니다.

const doc = Document.OpenFile('in.pdf');
const page = doc.Pages[0];

// Page number, right-aligned near the bottom-right corner.
const w = page.Rect[2] - page.Rect[0];
page.AddText(`Page ${page.Number}`, w - 40, 20, { fontSize: 10, align: 'right' });

// Semi-transparent diagonal watermark, centered on the page.
page.AddText('DRAFT', page.Rect[2] / 2, page.Rect[3] / 2, {
  font: 'Times-Bold', fontSize: 64, color: [0.7, 0.7, 0.7], opacity: 0.4, rotate: 45, align: 'center',
});

doc.WriteTo('out.pdf');

콘텐츠 스트림 내부 분석

parseContentStream()는 페이지의 원시 /Contents 스트림을 연산자/피연산자 쌍 목록으로 디코딩하고, serializeContentStream()는 편집된 연산자 목록을 다시 바이트로 변환합니다.

import { parseContentStream, serializeContentStream } from '@asposefoss/pdf';

const ops = parseContentStream(doc.Pages[0].Contents);
// ops: { operator: string, operands: PdfObject[], inlineImage?: {...} }[]
for (const op of ops) {
  if (op.operator === 'Tj') console.log('text op:', op.operands);
}
const bytes = serializeContentStream(ops);       // round-trips operators + operands

다중 열 텍스트 흐름

Page.AddTextBlock()는 긴 텍스트 문자열을 사각형 영역으로 흐르게 하고, 맞지 않은 텍스트를 반환합니다. 이 반환된 텍스트는 두 번째 호출에 전달하여 다른 열로 흐름을 이어갈 수 있습니다.

const rest = page.AddTextBlock(longText, [72, 600, 200, 150], {
  font: 'Times-Roman', fontSize: 11, align: 'justify', valign: 'top', leading: 14,
});
if (rest) page.AddTextBlock(rest, [300, 600, 200, 150]); // continue into a 2nd column

팁 및 모범 사례

  • 파일 경로에는 Document.OpenFile()를 사용하고, 메모리 내 Uint8Array 데이터에는 Document.Open()을 사용하세요.
  • 메서드 RemovePage() 및 ExtractPages()에 전달되는 페이지 번호는 1부터 시작하지만, doc.Pages는 0부터 시작하는 배열입니다.
  • 출력에서 xref-stream 및 object-stream 압축을 활성화하려면 { compressed: true }를 Document.WriteTo()에 전달하십시오.
  • Document.ExtractPages()는 페이지 번호의 중복을 허용하므로 동일한 원본 페이지가 결과에 여러 번 나타날 수 있습니다.
  • 좌표를 고정값으로 지정하는 대신 페이지의 실제 너비와 높이에 상대적인 위치를 계산하려면 page.Rect를 읽으십시오.

일반적인 문제

문제원인수정
Document.Open() / OpenFile()이 InvalidPasswordError을 발생시킵니다PDF가 비밀번호로 보호되어 있으며 비밀번호가 제공되지 않았거나(또는 잘못된 비밀번호가) 제공되었습니다{ password: '...' }을 Document.OpenFile() / Document.Open()에 전달하십시오
RemovePage()이(가) 잘못된 페이지를 제거합니다RemovePage()에 전달되는 페이지 번호는 1부터이며 0부터가 아닙니다1부터 시작하는 페이지 번호를 전달하세요, doc.Pages 배열 인덱싱과는 구별됩니다.
WriteTo() 출력이 예상보다 큽니다.기본 저장은 xref/object-stream 압축을 사용하지 않습니다.{ compressed: true }을(를) Document.WriteTo()에 전달하세요.

FAQ

Document.Open()은 파일 경로와 메모리 내 데이터 모두를 허용합니까?

Document.OpenFile()는 파일 경로에서 열고; Document.Open()는 메모리 내 바이트의 Uint8Array를 허용합니다.

페이지 번호가 0부터 시작합니까, 아니면 1부터 시작합니까?

두 경우 모두 가능합니다, API에 따라 다릅니다: doc.Pages은 순수 0 기반 배열이며, RemovePage() 및 ExtractPages()와 같은 메서드는 1 기반 페이지 번호를 사용합니다.

문서를 저장하면서 암호화할 수 있나요?

예 — encrypt 옵션을 WriteTo() / Save()에 algorithm: 'aes256' | 'aes128' | 'rc4'와 선택적인 사용자/소유자 비밀번호와 함께 전달하십시오.

출력 파일 크기를 어떻게 줄일 수 있나요?

{ compressed: true }을(를) Document.WriteTo()에 전달하여 xref-stream 및 object-stream 압축을 활성화합니다.

페이지의 원시 content-stream 연산자를 검사할 수 있나요?

예 — parseContentStream(doc.Pages[0].Contents)은 연산자 목록을 반환하고, serializeContentStream()은 편집된 목록을 다시 바이트로 변환합니다.


API Reference 요약

클래스 / 메서드설명
DocumentPDF 문서를 생성, 로드 및 저장하기 위한 중앙 진입점
Document.OpenFile() / Document.Open()파일 경로 또는 메모리 내 바이트에서 PDF 로드하기
Document.New()주어진 PageFormat 로 빈 문서를 시작합니다
Document.WriteTo() / Document.Save()문서를 파일 경로에 쓰거나 바이트를 반환합니다
Document.Split() / Document.Merge() / Document.ExtractPages()문서 간에 페이지를 분할, 병합 및 추출합니다
Document.Append() / Document.InsertPage()한 문서에서 다른 문서로 페이지를 복사
Page단일 PDF 페이지; 텍스트, 이미지, 주석 및 콘텐츠 스트림 메서드를 제공합니다
Page.AddText() / Page.AddTextBlock()페이지에 위치 지정된 텍스트 또는 흐르는 텍스트를 추가
parseContentStream() / serializeContentStream()페이지의 원시 콘텐츠 스트림 연산자를 구문 분석하고 다시 직렬화

참조

 한국어