Java PDF 편집기 라이브러리 (사용법 및 코드 예제)
IronPDF의 Java PDF 라이브러리는 Java 애플리케이션 내에서 PDF 문서를 편집하고 생성하는 강력한 도구입니다. 이 프로그램은 서명, HTML 바닥글, 워터마크 및 주석 추가와 같은 다양한 PDF 편집 기능을 간소화합니다.
IronPDF 사용하면 프로그래밍 방식으로 PDF 파일을 쉽게 생성하고, 코드를 효율적으로 디버깅하고, 다양한 지원 플랫폼 또는 환경에 프로젝트를 배포할 수 있습니다.
대부분의 Java PDF 라이브러리의 주요 목표는 PDF 파일을 동적으로 생성하는 것입니다. IronPDF 이러한 작업에 탁월하며, 사용자의 요구를 충족하는 다양한 기능을 제공합니다.
이 글에서는 IronPDF의 가장 중요한 기능 몇 가지를 코드 예제와 설명을 통해 자세히 살펴봅니다. 이 과정을 마치면 IronPDF 사용하여 Java 환경에서 PDF를 편집하는 방법을 확실히 이해하게 될 것이며, 이는 여러분의 PDF 편집 요구 사항에 완벽하게 부합할 것입니다.
Java PDF 편집기 라이브러리 사용 방법
- PDF 편집을 위한 Java 라이브러리를 설치하세요.
- `prependPdf` , `copyPages` , `removePages` 메서드를 사용하여 PDF를 추가, 복사 및 삭제할 수 있습니다.
- `merge` 메서드를 사용하여 PDF를 병합하고 `copyPages` 메서드를 사용하여 PDF를 분할합니다.
- 사용자 지정 용지 크기로 새 PDF를 생성하세요.
- PDF 메타데이터 편집
문서 구조 편집
PDF 문서 조작하기
IronPDF 특정 목차에 PDF를 추가하고, 페이지를 범위별로 또는 개별적으로 복사하고, 페이지를 쉽게 삭제할 수 있는 기능을 통해 PDF 관리를 간편하게 해줍니다. 이 모든 작업은 백그라운드에서 원활하게 처리됩니다.
페이지 추가
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
public class AddPagesExample {
public static void main(String[] args) {
try {
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
PdfDocument coverPagePdf = PdfDocument.renderHtmlAsPdf("<h1>Cover Page</h1><hr>");
PDF.prependPdf(coverPagePdf);
PDF.saveAs(Paths.get("report_with_cover.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
public class AddPagesExample {
public static void main(String[] args) {
try {
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
PdfDocument coverPagePdf = PdfDocument.renderHtmlAsPdf("<h1>Cover Page</h1><hr>");
PDF.prependPdf(coverPagePdf);
PDF.saveAs(Paths.get("report_with_cover.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
복사 페이지
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
public class CopyPagesExample {
public static void main(String[] args) {
try {
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
PDF.copyPages(0, 1).saveAs("report_highlight.pdf");
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
public class CopyPagesExample {
public static void main(String[] args) {
try {
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
PDF.copyPages(0, 1).saveAs("report_highlight.pdf");
} catch (IOException e) {
e.printStackTrace();
}
}
}
페이지 삭제
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
public class DeletePagesExample {
public static void main(String[] args) {
try {
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
PDF.removePages(PageSelection.lastPage()).saveAs(Paths.get("assets/lastPageRemove.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
public class DeletePagesExample {
public static void main(String[] args) {
try {
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
PDF.removePages(PageSelection.lastPage()).saveAs(Paths.get("assets/lastPageRemove.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
표지를 첨부하세요
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.headerfooter.HeaderFooterOptions;
import com.ironsoftware.ironpdf.headerfooter.TextHeaderFooter;
import java.io.IOException;
import java.nio.file.Paths;
public class AttachCoverPageExample {
public static void main(String[] args) {
// Create a Sample Cover Page using RenderHtmlAsPdf
PdfDocument coverPage = PdfDocument.renderHtmlAsPdf("<h1>This is a Cover Page</h1>");
PdfDocument webpage = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
// Set the page number of the PDF document to be created to 2.
HeaderFooterOptions headerFooterOptions = new HeaderFooterOptions();
headerFooterOptions.setFirstPageNumber(1);
TextHeaderFooter footer = new TextHeaderFooter();
footer.setLeftText("");
footer.setCenterText("Page {page}");
footer.setRightText("");
webpage.addTextFooter(footer, headerFooterOptions);
// Convert a web page's content to a PDF document.
// Merge the cover page with the web page and save the new PDF to the filesystem.
try {
PdfDocument.merge(coverPage, webpage).saveAs(Paths.get("assets/cover_page_pdf.pdf"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.headerfooter.HeaderFooterOptions;
import com.ironsoftware.ironpdf.headerfooter.TextHeaderFooter;
import java.io.IOException;
import java.nio.file.Paths;
public class AttachCoverPageExample {
public static void main(String[] args) {
// Create a Sample Cover Page using RenderHtmlAsPdf
PdfDocument coverPage = PdfDocument.renderHtmlAsPdf("<h1>This is a Cover Page</h1>");
PdfDocument webpage = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
// Set the page number of the PDF document to be created to 2.
HeaderFooterOptions headerFooterOptions = new HeaderFooterOptions();
headerFooterOptions.setFirstPageNumber(1);
TextHeaderFooter footer = new TextHeaderFooter();
footer.setLeftText("");
footer.setCenterText("Page {page}");
footer.setRightText("");
webpage.addTextFooter(footer, headerFooterOptions);
// Convert a web page's content to a PDF document.
// Merge the cover page with the web page and save the new PDF to the filesystem.
try {
PdfDocument.merge(coverPage, webpage).saveAs(Paths.get("assets/cover_page_pdf.pdf"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
IronPDF 에서 PDF 문서에 표지를 첨부하는 방법 에 대해 자세히 알아보세요.
PDF 병합 및 분할
IronPDF Java는 사용자 친화적인 API를 사용하여 여러 PDF 파일을 하나로 병합하거나 기존 PDF 파일을 분할하는 과정을 간소화합니다.
여러 개의 기존 PDF 문서를 하나의 PDF 문서로 병합
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
public class MergePdfsExample {
public static void main(String[] args) {
String htmlA = "<p> [PDF_A] </p>" +
"<p> [PDF_A] 1st Page </p>" +
"<div style='page-break-after: always;'></div>" +
"<p> [PDF_A] 2nd Page</p>";
String htmlB = "<p> [PDF_B] </p>" +
"<p> [PDF_B] 1st Page </p>" +
"<div style='page-break-after: always;'></div>" +
"<p> [PDF_B] 2nd Page</p>";
PdfDocument pdfA = PdfDocument.renderHtmlAsPdf(htmlA);
PdfDocument pdfB = PdfDocument.renderHtmlAsPdf(htmlB);
PdfDocument merged = PdfDocument.merge(pdfA, pdfB);
merged.saveAs(Paths.get("assets/merged.pdf"));
}
}
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
public class MergePdfsExample {
public static void main(String[] args) {
String htmlA = "<p> [PDF_A] </p>" +
"<p> [PDF_A] 1st Page </p>" +
"<div style='page-break-after: always;'></div>" +
"<p> [PDF_A] 2nd Page</p>";
String htmlB = "<p> [PDF_B] </p>" +
"<p> [PDF_B] 1st Page </p>" +
"<div style='page-break-after: always;'></div>" +
"<p> [PDF_B] 2nd Page</p>";
PdfDocument pdfA = PdfDocument.renderHtmlAsPdf(htmlA);
PdfDocument pdfB = PdfDocument.renderHtmlAsPdf(htmlB);
PdfDocument merged = PdfDocument.merge(pdfA, pdfB);
merged.saveAs(Paths.get("assets/merged.pdf"));
}
}
PDF 분할 및 페이지 추출
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
public class SplitPdfExample {
public static void main(String[] args) {
try {
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
PdfDocument copied = PDF.copyPage(0);
copied.saveAs("assets/Split.pdf");
} catch (IOException e) {
e.printStackTrace();
}
}
}
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
public class SplitPdfExample {
public static void main(String[] args) {
try {
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
PdfDocument copied = PDF.copyPage(0);
copied.saveAs("assets/Split.pdf");
} catch (IOException e) {
e.printStackTrace();
}
}
}
PDF 문서의 사용자 지정 크기를 설정하세요
IronPDF 사용하면 개발자는 일반적인 A4 크기(8½ x 11인치 또는 21.59 x 27.94cm)를 넘어선 비표준 크기의 PDF 문서를 만들 수 있습니다.
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import com.ironsoftware.ironpdf.render.PaperSize;
import java.io.IOException;
import java.nio.file.Paths;
public class CustomSizeExample {
public static void main(String[] args) {
String html = "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>";
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
renderOptions.setPaperSize(PaperSize.Custom);
/*
* Setting page sizes using different measuring units:
* 1. setCustomPaperWidth( width ) / setCustomPaperHeight( height ): for inches
* 2. setCustomPaperSizeInCentimeters( width, height ): for centimeters.
* 3. setCustomPaperSizeInMillimeters( width, height ): for millimeters
* 4. setCustomPaperSizeInPixelsOrPoints( width, height ): for pixels/points
* */
renderOptions.setCustomPaperSizeInCentimeters(13.97, 13.97);
PdfDocument.renderHtmlAsPdf(html, renderOptions).saveAs(Paths.get("assets/CustomPaperSize.pdf"));
}
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import com.ironsoftware.ironpdf.render.PaperSize;
import java.io.IOException;
import java.nio.file.Paths;
public class CustomSizeExample {
public static void main(String[] args) {
String html = "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>";
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
renderOptions.setPaperSize(PaperSize.Custom);
/*
* Setting page sizes using different measuring units:
* 1. setCustomPaperWidth( width ) / setCustomPaperHeight( height ): for inches
* 2. setCustomPaperSizeInCentimeters( width, height ): for centimeters.
* 3. setCustomPaperSizeInMillimeters( width, height ): for millimeters
* 4. setCustomPaperSizeInPixelsOrPoints( width, height ): for pixels/points
* */
renderOptions.setCustomPaperSizeInCentimeters(13.97, 13.97);
PdfDocument.renderHtmlAsPdf(html, renderOptions).saveAs(Paths.get("assets/CustomPaperSize.pdf"));
}
}
IronPDF 에서 PDF 파일 크기를 사용자 지정 하는 데 유용한 추가 팁을 소개합니다.
PDF 방향 설정
IronPDF for Java는 새 PDF 파일과 기존 PDF 파일 모두에서 페이지 방향을 수정할 수 있도록 해줍니다. 기본적으로, IronPDF로 생성된 새 PDF는 세로 방향으로 설정되지만, 개발자는 콘텐츠(HTML, RTF, URL 등)를 PDF로 변환할 때 ChromePdfRenderOptions 인스턴스를 사용하여 이를 변경할 수 있습니다.
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
import com.ironsoftware.ironpdf.page.PageRotation;
import com.ironsoftware.ironpdf.render.*;
import java.io.IOException;
import java.nio.file.Paths;
public class SetOrientationExample {
public static void main(String[] args) {
// Load an existing PDF
PdfDocument existingPdf = PdfDocument.fromFile("assets/sample.pdf");
// Get the orientation of the first page of the existing PDF document.
PageRotation firstPageRotation = existingPdf.getPagesInfo().get(0).getPageRotation();
System.out.println(firstPageRotation);
// Rotate the first page of the document only 90 degrees clockwise.
existingPdf.rotatePage(PageRotation.CLOCKWISE_90, PageSelection.firstPage());
// Rotate all pages of the document clockwise.
existingPdf.rotateAllPages(PageRotation.CLOCKWISE_270);
existingPdf.saveAs(Paths.get("assets/ExistingPdfRotated.pdf"));
}
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
import com.ironsoftware.ironpdf.page.PageRotation;
import com.ironsoftware.ironpdf.render.*;
import java.io.IOException;
import java.nio.file.Paths;
public class SetOrientationExample {
public static void main(String[] args) {
// Load an existing PDF
PdfDocument existingPdf = PdfDocument.fromFile("assets/sample.pdf");
// Get the orientation of the first page of the existing PDF document.
PageRotation firstPageRotation = existingPdf.getPagesInfo().get(0).getPageRotation();
System.out.println(firstPageRotation);
// Rotate the first page of the document only 90 degrees clockwise.
existingPdf.rotatePage(PageRotation.CLOCKWISE_90, PageSelection.firstPage());
// Rotate all pages of the document clockwise.
existingPdf.rotateAllPages(PageRotation.CLOCKWISE_270);
existingPdf.saveAs(Paths.get("assets/ExistingPdfRotated.pdf"));
}
}
자세한 내용은 IronPDF 웹사이트의 PDF 방향 설정 튜토리얼을 참조하세요.
PDF의 사용자 지정 여백 설정
IronPDF 새 PDF 파일을 생성할 때 모든 면(상단, 하단, 좌측, 우측)에 기본적으로 25mm의 여백을 적용합니다. 하지만 개발자는 IronPDF 사용하여 각 여백을 특정 측정값으로 사용자 지정할 수 있습니다.
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import java.io.IOException;
import java.nio.file.Paths;
public class CustomMarginsExample {
public static void main(String[] args) {
// Set Margins (in millimeters)
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
renderOptions.setMarginTop(40);
renderOptions.setMarginLeft(20);
renderOptions.setMarginRight(20);
renderOptions.setMarginBottom(40);
try {
PdfDocument.renderHtmlFileAsPdf("assets/wikipedia.html", renderOptions).saveAs(Paths.get("assets/MyContent.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import java.io.IOException;
import java.nio.file.Paths;
public class CustomMarginsExample {
public static void main(String[] args) {
// Set Margins (in millimeters)
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
renderOptions.setMarginTop(40);
renderOptions.setMarginLeft(20);
renderOptions.setMarginRight(20);
renderOptions.setMarginBottom(40);
try {
PdfDocument.renderHtmlFileAsPdf("assets/wikipedia.html", renderOptions).saveAs(Paths.get("assets/MyContent.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
IronPDF 웹사이트를 방문하여 PDF 문서의 사용자 지정 여백 설정 에 대해 자세히 알아보세요.
PDF 문서를 이미지로 변환
IronPDF 로드된 PDF 파일의 페이지, 변환된 원본 콘텐츠 또는 머리글, 바닥글, 여백 등이 포함된 수정된 PDF를 이미지로 내보내 파일 시스템에 저장하거나 데이터베이스에 저장하거나 네트워크를 통해 전송할 수 있습니다.
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
import com.ironsoftware.ironpdf.image.ToImageOptions;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;
public class ConvertPdfToImagesExample {
public static void main(String[] args) {
try {
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/composite.pdf"));
// Extract all the pages from the PDF file.
List<BufferedImage> extractedImages = pdf.toBufferedImages();
// With the ToImageOptions object, specify maximum image dimensions for each
// extracted image, as well as their DPI
ToImageOptions rasterOptions = new ToImageOptions();
rasterOptions.setImageMaxHeight(100);
rasterOptions.setImageMaxWidth(100);
// Call the toBufferedImage method along with a PageSelection object to choose the pages from which to
// extract the images
//
// Available PageSelection methods include: allPages, lastPage, firstPage, singlePage(int pageIndex),
// and pageRange(int startingPage, int endingPage)
List<BufferedImage> sizedExtractedImages = pdf.toBufferedImages(rasterOptions, PageSelection.allPages());
// Save all the extracted images to a file location
int i = 1;
for (BufferedImage extractedImage : sizedExtractedImages) {
String fileName = "assets/images/" + i++ + ".png";
ImageIO.write(extractedImage, "PNG", new File(fileName));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
import com.ironsoftware.ironpdf.image.ToImageOptions;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;
public class ConvertPdfToImagesExample {
public static void main(String[] args) {
try {
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/composite.pdf"));
// Extract all the pages from the PDF file.
List<BufferedImage> extractedImages = pdf.toBufferedImages();
// With the ToImageOptions object, specify maximum image dimensions for each
// extracted image, as well as their DPI
ToImageOptions rasterOptions = new ToImageOptions();
rasterOptions.setImageMaxHeight(100);
rasterOptions.setImageMaxWidth(100);
// Call the toBufferedImage method along with a PageSelection object to choose the pages from which to
// extract the images
//
// Available PageSelection methods include: allPages, lastPage, firstPage, singlePage(int pageIndex),
// and pageRange(int startingPage, int endingPage)
List<BufferedImage> sizedExtractedImages = pdf.toBufferedImages(rasterOptions, PageSelection.allPages());
// Save all the extracted images to a file location
int i = 1;
for (BufferedImage extractedImage : sizedExtractedImages) {
String fileName = "assets/images/" + i++ + ".png";
ImageIO.write(extractedImage, "PNG", new File(fileName));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
배경과 전경을 추가하세요
IronPDF는 addBackgroundPdf 및 addForegroundPdf 메서드를 제공하여 PDF에 특정 배경 또는 전경 요소 추가할 수 있습니다. 이러한 방법을 통해 개발자는 한 PDF의 콘텐츠를 다른 PDF의 배경이나 전경으로 삽입할 수 있으므로 공통 디자인 템플릿을 기반으로 PDF 모음을 효율적으로 생성할 수 있습니다.
PDF를 배경으로 추가
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
public class AddBackgroundExample {
public static void main(String[] args) {
try {
// Load background PDFs from the filesystem (or create them programmatically)
PdfDocument backgroundPdf = PdfDocument.fromFile(Paths.get("assets/MyBackground.pdf"));
// Render content (HTML, URL, etc) as a PDF Document
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
// Add the background PDFs to the newly-rendered document.
pdf.addBackgroundPdf(backgroundPdf);
pdf.saveAs(Paths.get("assets/BackgroundPdf.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
public class AddBackgroundExample {
public static void main(String[] args) {
try {
// Load background PDFs from the filesystem (or create them programmatically)
PdfDocument backgroundPdf = PdfDocument.fromFile(Paths.get("assets/MyBackground.pdf"));
// Render content (HTML, URL, etc) as a PDF Document
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
// Add the background PDFs to the newly-rendered document.
pdf.addBackgroundPdf(backgroundPdf);
pdf.saveAs(Paths.get("assets/BackgroundPdf.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
PDF를 전경 이미지로 추가
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
public class AddForegroundExample {
public static void main(String[] args) {
try {
PdfDocument foregroundPdf = PdfDocument.fromFile(Paths.get("assets/MyForeground.pdf"));
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
pdf.addForegroundPdf(foregroundPdf);
pdf.saveAs(Paths.get("assets/BackgroundForegroundPdf.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
public class AddForegroundExample {
public static void main(String[] args) {
try {
PdfDocument foregroundPdf = PdfDocument.fromFile(Paths.get("assets/MyForeground.pdf"));
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
pdf.addForegroundPdf(foregroundPdf);
pdf.saveAs(Paths.get("assets/BackgroundForegroundPdf.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
문서 속성 편집
PDF 메타데이터 추가 및 사용
IronPDF PDF 메타데이터 및 보안 기능을 수정할 수 있는 기능을 제공하며, 여기에는 PDF를 읽기 전용, 인쇄 불가, 암호 보호 및 암호화하는 기능이 포함됩니다. Java용 IronPDF에서 MetadataManager를 사용하여 PDF의 메타데이터를 접근하고 편집할 수 있습니다. MetadataManager 클래스는 메타데이터 콘텐츠에 대한 직접적인 접근을 제공하고 개발자가 동일한 이름의 getter와 setter를 통해 일반 메타데이터 속성을 읽고 편집할 수 있도록 합니다.
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.metadata.MetadataManager;
import com.ironsoftware.ironpdf.security.PdfPrintSecurity;
import com.ironsoftware.ironpdf.security.SecurityOptions;
import com.ironsoftware.ironpdf.security.SecurityManager;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Date;
public class EditMetadataExample {
public static void main(String[] args) {
try {
// Open an encrypted file (or create a new one from HTML)
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/encrypted.pdf"), "password");
// Edit file metadata
MetadataManager metadata = pdf.getMetadata();
metadata.setAuthor("Satoshi Nakamoto");
metadata.setKeywords("SEO, Friendly");
metadata.setModifiedDate(new Date().toString());
// Edit file security settings
// The code below makes the PDF read-only and disallows users to copy, paste, and print
SecurityOptions securityOptions = new SecurityOptions();
securityOptions.setAllowUserCopyPasteContent(false);
securityOptions.setAllowUserAnnotations(false);
securityOptions.setAllowUserPrinting(PdfPrintSecurity.FULL_PRINT_RIGHTS);
securityOptions.setAllowUserFormData(false);
securityOptions.setOwnerPassword("top-secret");
securityOptions.setUserPassword("sharable");
// Change or set the document encryption password
SecurityManager securityManager = pdf.getSecurity();
securityManager.removePasswordsAndEncryption();
securityManager.makePdfDocumentReadOnly("secret-key");
securityManager.setSecurityOptions(securityOptions);
pdf.saveAs(Paths.get("assets/secured.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.metadata.MetadataManager;
import com.ironsoftware.ironpdf.security.PdfPrintSecurity;
import com.ironsoftware.ironpdf.security.SecurityOptions;
import com.ironsoftware.ironpdf.security.SecurityManager;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Date;
public class EditMetadataExample {
public static void main(String[] args) {
try {
// Open an encrypted file (or create a new one from HTML)
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/encrypted.pdf"), "password");
// Edit file metadata
MetadataManager metadata = pdf.getMetadata();
metadata.setAuthor("Satoshi Nakamoto");
metadata.setKeywords("SEO, Friendly");
metadata.setModifiedDate(new Date().toString());
// Edit file security settings
// The code below makes the PDF read-only and disallows users to copy, paste, and print
SecurityOptions securityOptions = new SecurityOptions();
securityOptions.setAllowUserCopyPasteContent(false);
securityOptions.setAllowUserAnnotations(false);
securityOptions.setAllowUserPrinting(PdfPrintSecurity.FULL_PRINT_RIGHTS);
securityOptions.setAllowUserFormData(false);
securityOptions.setOwnerPassword("top-secret");
securityOptions.setUserPassword("sharable");
// Change or set the document encryption password
SecurityManager securityManager = pdf.getSecurity();
securityManager.removePasswordsAndEncryption();
securityManager.makePdfDocumentReadOnly("secret-key");
securityManager.setSecurityOptions(securityOptions);
pdf.saveAs(Paths.get("assets/secured.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
디지털 서명
Java용 IronPDF는 .pfx 또는 .p12 형식의 X509Certificate2 디지털 인증서를 사용하여 새로운 또는 기존의 PDF 파일에 대한 안전한 서명을 허용합니다. PDF 파일에 디지털 서명을 하면 진위가 보장되어 적절한 인증서 검증 없이는 파일 내용이 변경되는 것을 방지할 수 있습니다. 이는 문서의 신뢰성을 높여줍니다.
서명 인증서를 무료로 생성하는 방법으로는 Adobe Reader 의 디지털 ID 튜토리얼에서 제공하는 지침을 따르는 것이 있습니다.
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.signature.Signature;
import com.ironsoftware.ironpdf.signature.SignatureManager;
public class DigitalSignatureExample {
public static void main(String[] args) {
try {
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
// Load the X509Certificate2 digitals certificates from .pfx or .p12 formats
File path = new File("assets/Ironpdf.pfx");
byte[] certificate = new byte[(int) path.length()];
// Sign PDF with a specific signature
Signature signature = new Signature(certificate, "1234");
SignatureManager manager = PDF.getSignature();
manager.signPdfWithSignature(signature);
PDF.saveAs(Paths.get("assets/signed_sample.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.signature.Signature;
import com.ironsoftware.ironpdf.signature.SignatureManager;
public class DigitalSignatureExample {
public static void main(String[] args) {
try {
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
// Load the X509Certificate2 digitals certificates from .pfx or .p12 formats
File path = new File("assets/Ironpdf.pfx");
byte[] certificate = new byte[(int) path.length()];
// Sign PDF with a specific signature
Signature signature = new Signature(certificate, "1234");
SignatureManager manager = PDF.getSignature();
manager.signPdfWithSignature(signature);
PDF.saveAs(Paths.get("assets/signed_sample.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
PDF 압축
IronPDF는 compressImages 메서드를 통해 PdfDocument 클래스에서 대용량 이미지를 가진 PDF를 쉽게 압축할 수 있습니다. 이러한 최적화를 통해 이메일 및 기타 통신 채널을 통해 PDF를 전송할 때 저장 공간과 비용을 크게 절감할 수 있습니다.
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
public class CompressPdfExample {
public static void main(String[] args) {
try {
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/document.pdf"));
// Valid image compression values range from 1 to 100, where 100 represents 100% of the original image quality.
pdf.compressImages(60);
pdf.saveAs(Paths.get("assets/document_compressed.pdf"));
// The second, optional parameter can scale down the image resolution according to its visible size in the PDF document.
// Note that this may cause distortion with some image configurations.
pdf.compressImages(90, true);
pdf.saveAs(Paths.get("assets/document_scaled_compressed.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
public class CompressPdfExample {
public static void main(String[] args) {
try {
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/document.pdf"));
// Valid image compression values range from 1 to 100, where 100 represents 100% of the original image quality.
pdf.compressImages(60);
pdf.saveAs(Paths.get("assets/document_compressed.pdf"));
// The second, optional parameter can scale down the image resolution according to its visible size in the PDF document.
// Note that this may cause distortion with some image configurations.
pdf.compressImages(90, true);
pdf.saveAs(Paths.get("assets/document_scaled_compressed.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
PDF 콘텐츠 편집
머리글과 바닥글 추가
IronPDF는 ChromePdfRenderOptions 및 HtmlHeaderFooter 클래스를 사용하여 사용자 정의 HTML 헤더와 푸터를 추가할 수 있습니다. 헤더/푸터의 왼쪽, 오른쪽 또는 중앙 영역에 대한 텍스트를 지정할 수 있는 TextHeaderFooter 클래스를 통해 사용자 정의 텍스트 헤더와 푸터도 지원됩니다. {날짜}, {시간}, {페이지} 와 같은 템플릿 태그는 사용자 지정 텍스트와 함께 사용할 수 있습니다.
HTML 헤더 및 푸터
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.headerfooter.HtmlHeaderFooter;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class HtmlHeaderFooterExample {
public static void main(String[] args) {
try {
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
// Build a footer using HTML
// Merge Fields are: {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
HtmlHeaderFooter footer = new HtmlHeaderFooter();
footer.setMaxHeight(15); // millimeters
footer.setHtmlFragment("<center><i>{page} of {total-pages}</i></center>");
footer.setDrawDividerLine(true);
pdf.addHtmlFooter(footer);
List<PdfDocument> pdfs = new ArrayList<>();
// Build a header using an image asset
// Note the use of BaseUrl to set a relative path to the assets
HtmlHeaderFooter header = new HtmlHeaderFooter();
header.setMaxHeight(20); // millimeters
header.setHtmlFragment("<img src=\"logo.png\" />");
header.setBaseUrl("./assets/");
pdf.addHtmlHeader(header);
pdf.saveAs(Paths.get("assets/html_headers_footers.pdf"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.headerfooter.HtmlHeaderFooter;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class HtmlHeaderFooterExample {
public static void main(String[] args) {
try {
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
// Build a footer using HTML
// Merge Fields are: {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
HtmlHeaderFooter footer = new HtmlHeaderFooter();
footer.setMaxHeight(15); // millimeters
footer.setHtmlFragment("<center><i>{page} of {total-pages}</i></center>");
footer.setDrawDividerLine(true);
pdf.addHtmlFooter(footer);
List<PdfDocument> pdfs = new ArrayList<>();
// Build a header using an image asset
// Note the use of BaseUrl to set a relative path to the assets
HtmlHeaderFooter header = new HtmlHeaderFooter();
header.setMaxHeight(20); // millimeters
header.setHtmlFragment("<img src=\"logo.png\" />");
header.setBaseUrl("./assets/");
pdf.addHtmlHeader(header);
pdf.saveAs(Paths.get("assets/html_headers_footers.pdf"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
텍스트 머리글 및 바닥글
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.font.FontTypes;
import com.ironsoftware.ironpdf.headerfooter.TextHeaderFooter;
import com.ironsoftware.ironpdf.headerfooter.HeaderFooterOptions;
import java.io.IOException;
import java.nio.file.Paths;
public class TextHeaderFooterExample {
public static void main(String[] args) {
try {
// Initialize HeaderFooterOptions object.
HeaderFooterOptions options = new HeaderFooterOptions();
PdfDocument pdf = PdfDocument.renderUrlAsPdf("http://www.google.com");
// Add a header to every page easily
// Mergeable fields are:
// {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
options.setFirstPageNumber(1); // use 2 if a coverpage will be appended
TextHeaderFooter textHeader = new TextHeaderFooter();
textHeader.setDrawDividerLine(true);
textHeader.setCenterText("{url}");
textHeader.setFont(FontTypes.getHelvetica());
textHeader.setFontSize(12);
pdf.addTextHeader(textHeader, options);
// Add a footer too
TextHeaderFooter textFooter = new TextHeaderFooter();
textFooter.setDrawDividerLine(true);
textFooter.setFont(FontTypes.getArial());
textFooter.setFontSize(10);
textFooter.setLeftText("{date} {time}");
textFooter.setRightText("{page} of {total-pages}");
pdf.addTextFooter(textFooter, options);
pdf.saveAs(Paths.get("assets/text_headers_footers.pdf"));
} catch (IOException e) {
System.out.println("Failed to save PDF");
throw new RuntimeException(e);
}
}
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.font.FontTypes;
import com.ironsoftware.ironpdf.headerfooter.TextHeaderFooter;
import com.ironsoftware.ironpdf.headerfooter.HeaderFooterOptions;
import java.io.IOException;
import java.nio.file.Paths;
public class TextHeaderFooterExample {
public static void main(String[] args) {
try {
// Initialize HeaderFooterOptions object.
HeaderFooterOptions options = new HeaderFooterOptions();
PdfDocument pdf = PdfDocument.renderUrlAsPdf("http://www.google.com");
// Add a header to every page easily
// Mergeable fields are:
// {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
options.setFirstPageNumber(1); // use 2 if a coverpage will be appended
TextHeaderFooter textHeader = new TextHeaderFooter();
textHeader.setDrawDividerLine(true);
textHeader.setCenterText("{url}");
textHeader.setFont(FontTypes.getHelvetica());
textHeader.setFontSize(12);
pdf.addTextHeader(textHeader, options);
// Add a footer too
TextHeaderFooter textFooter = new TextHeaderFooter();
textFooter.setDrawDividerLine(true);
textFooter.setFont(FontTypes.getArial());
textFooter.setFontSize(10);
textFooter.setLeftText("{date} {time}");
textFooter.setRightText("{page} of {total-pages}");
pdf.addTextFooter(textFooter, options);
pdf.saveAs(Paths.get("assets/text_headers_footers.pdf"));
} catch (IOException e) {
System.out.println("Failed to save PDF");
throw new RuntimeException(e);
}
}
}
책갈피
개발자는 BookmarkManager 클래스를 사용하여 PDF 내에서 책갈피의 계층 구조를 만들 수 있으며, 사용자는 쉽게 다른 섹션으로 이동할 수 있습니다. 새 책갈피를 추가하려면 책갈피의 제목과 페이지 번호를 지정하여 add 메서드를 사용합니다. 책갈피는 중첩하여 더욱 체계적인 구조를 만들 수 있습니다.
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.bookmark.Bookmark;
import com.ironsoftware.ironpdf.bookmark.BookmarkManager;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;
public class BookmarksExample {
public static void main(String[] args) {
try {
// Load an existing PDF from the file system (or create a new one from HTML)
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/book.pdf"));
// Add top-level bookmarks to pages of the PDF using their page indices
BookmarkManager bookmarks = pdf.getBookmark();
bookmarks.addBookMarkAtEnd("Author's Note", 2);
bookmarks.addBookMarkAtEnd("Table of Contents", 3);
bookmarks.addBookMarkAtEnd("Summary", 10);
bookmarks.addBookMarkAtEnd("References", 12);
// Retrieve a reference to the Summary bookmark so that we can add a sublist of bookmarks to it.
List<Bookmark> bookmarkList = bookmarks.getBookmarks();
Bookmark bookmark = bookmarkList.get(2);
bookmark.addChildBookmark("Conclusion", 11);
// Save the PDF to the filesystem
pdf.saveAs(Paths.get("assets/bookmarked.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.bookmark.Bookmark;
import com.ironsoftware.ironpdf.bookmark.BookmarkManager;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;
public class BookmarksExample {
public static void main(String[] args) {
try {
// Load an existing PDF from the file system (or create a new one from HTML)
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/book.pdf"));
// Add top-level bookmarks to pages of the PDF using their page indices
BookmarkManager bookmarks = pdf.getBookmark();
bookmarks.addBookMarkAtEnd("Author's Note", 2);
bookmarks.addBookMarkAtEnd("Table of Contents", 3);
bookmarks.addBookMarkAtEnd("Summary", 10);
bookmarks.addBookMarkAtEnd("References", 12);
// Retrieve a reference to the Summary bookmark so that we can add a sublist of bookmarks to it.
List<Bookmark> bookmarkList = bookmarks.getBookmarks();
Bookmark bookmark = bookmarkList.get(2);
bookmark.addChildBookmark("Conclusion", 11);
// Save the PDF to the filesystem
pdf.saveAs(Paths.get("assets/bookmarked.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
주석 추가 및 편집
IronPDF는 AnnotationManager 및 AnnotationOptions 클래스를 사용하여 PDF의 특정 페이지에 "스티키 노트" 스타일의 주석을 추가할 수 있습니다. 텍스트와 (x, y) 좌표를 AnnotationOptions 생성자에 제공하여 텍스트 기반 주석을 생성한 다음 AnnotationManager의 addTextAnnotation 메서드를 사용하여 원하는 페이지에 주석을 추가하세요.
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.annotation.AnnotationIcon;
import com.ironsoftware.ironpdf.annotation.AnnotationManager;
import com.ironsoftware.ironpdf.annotation.AnnotationOptions;
import java.io.IOException;
import java.nio.file.Paths;
public class AnnotationExample {
public static void main(String[] args) {
try {
// Create a new PDF or load an existing one from the filesystem
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/example.pdf"));
// Create an annotation to be placed at a specific location on a page.
AnnotationOptions annotation = new AnnotationOptions(
"This is a major title", // Title of the annotation
"This is the long 'sticky note' comment content...", // Content of the annotation
150, // x-axis coordinate location
250 // y-axis coordinate location
);
annotation.setIcon(AnnotationIcon.HELP);
annotation.setOpacity(0.9);
annotation.setPrintable(false);
annotation.setHidden(false);
annotation.setOpen(true);
annotation.setReadonly(true);
annotation.setRotateable(true);
// Add the annotation to a specific page of the PDF
AnnotationManager annotationManager = pdf.getAnnotation();
annotationManager.addTextAnnotation(annotation, 0);
// Save the PDF with the modifications
pdf.saveAs(Paths.get("assets/annotated.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.annotation.AnnotationIcon;
import com.ironsoftware.ironpdf.annotation.AnnotationManager;
import com.ironsoftware.ironpdf.annotation.AnnotationOptions;
import java.io.IOException;
import java.nio.file.Paths;
public class AnnotationExample {
public static void main(String[] args) {
try {
// Create a new PDF or load an existing one from the filesystem
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/example.pdf"));
// Create an annotation to be placed at a specific location on a page.
AnnotationOptions annotation = new AnnotationOptions(
"This is a major title", // Title of the annotation
"This is the long 'sticky note' comment content...", // Content of the annotation
150, // x-axis coordinate location
250 // y-axis coordinate location
);
annotation.setIcon(AnnotationIcon.HELP);
annotation.setOpacity(0.9);
annotation.setPrintable(false);
annotation.setHidden(false);
annotation.setOpen(true);
annotation.setReadonly(true);
annotation.setRotateable(true);
// Add the annotation to a specific page of the PDF
AnnotationManager annotationManager = pdf.getAnnotation();
annotationManager.addTextAnnotation(annotation, 0);
// Save the PDF with the modifications
pdf.saveAs(Paths.get("assets/annotated.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
스탬핑 및 워터마킹
IronPDF for Java는 광범위한 스탬프 및 워터마킹 기능을 제공하는 강력한 API를 갖추고 있습니다. 개발자는 사용하기 쉬운 인터페이스를 통해 PDF에 이미지와 HTML 스탬프를 빠르게 추가할 수 있습니다. 회사 로고, 기밀 유지 고지 또는 고유 식별자가 필요하든 IronPDF 모든 것을 지원하여 PDF에 쉽고 전문적으로 스탬프를 추가할 수 있도록 해줍니다.
PDF에 텍스트를 스탬프로 추가하기
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.TextStamper;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;
public class StampTextExample {
public static void main(String[] args) {
try {
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
TextStamper stamper1 = new TextStamper();
stamper1.setText("Hello World! Stamp One Here!");
stamper1.setFontFamily("Bungee Spice");
stamper1.setUseGoogleFont(true);
stamper1.setFontSize(100);
stamper1.setBold(true);
stamper1.setItalic(false);
stamper1.setVerticalAlignment(VerticalAlignment.TOP);
pdf.applyStamp(stamper1);
pdf.saveAs(Paths.get("assets/stamped_sample.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.TextStamper;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;
public class StampTextExample {
public static void main(String[] args) {
try {
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
TextStamper stamper1 = new TextStamper();
stamper1.setText("Hello World! Stamp One Here!");
stamper1.setFontFamily("Bungee Spice");
stamper1.setUseGoogleFont(true);
stamper1.setFontSize(100);
stamper1.setBold(true);
stamper1.setItalic(false);
stamper1.setVerticalAlignment(VerticalAlignment.TOP);
pdf.applyStamp(stamper1);
pdf.saveAs(Paths.get("assets/stamped_sample.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
PDF에 이미지 삽입하기
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
import com.ironsoftware.ironpdf.stamp.ImageStamper;
public class StampImageExample {
public static void main(String[] args) {
try {
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
ImageStamper imageStamper = new ImageStamper(Paths.get("assets/logo.png"));
// Apply to every page, one page, or some pages
pdf.applyStamp(imageStamper);
pdf.applyStamp(imageStamper, PageSelection.singlePage(2));
pdf.applyStamp(imageStamper, PageSelection.pageRange(0, 2));
pdf.saveAs(Paths.get("assets/image_stamped_sample.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
import com.ironsoftware.ironpdf.stamp.ImageStamper;
public class StampImageExample {
public static void main(String[] args) {
try {
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
ImageStamper imageStamper = new ImageStamper(Paths.get("assets/logo.png"));
// Apply to every page, one page, or some pages
pdf.applyStamp(imageStamper);
pdf.applyStamp(imageStamper, PageSelection.singlePage(2));
pdf.applyStamp(imageStamper, PageSelection.pageRange(0, 2));
pdf.saveAs(Paths.get("assets/image_stamped_sample.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
PDF 파일에 바코드를 찍으세요
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.BarcodeEncoding;
import com.ironsoftware.ironpdf.stamp.BarcodeStamper;
import com.ironsoftware.ironpdf.stamp.HorizontalAlignment;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;
public class StampBarcodeExample {
public static void main(String[] args) {
try {
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
BarcodeStamper barcodeStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.Code39);
barcodeStamp.setHorizontalAlignment(HorizontalAlignment.LEFT);
barcodeStamp.setVerticalAlignment(VerticalAlignment.BOTTOM);
pdf.applyStamp(barcodeStamp);
pdf.saveAs(Paths.get("assets/barcode_stamped_sample.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.BarcodeEncoding;
import com.ironsoftware.ironpdf.stamp.BarcodeStamper;
import com.ironsoftware.ironpdf.stamp.HorizontalAlignment;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;
public class StampBarcodeExample {
public static void main(String[] args) {
try {
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
BarcodeStamper barcodeStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.Code39);
barcodeStamp.setHorizontalAlignment(HorizontalAlignment.LEFT);
barcodeStamp.setVerticalAlignment(VerticalAlignment.BOTTOM);
pdf.applyStamp(barcodeStamp);
pdf.saveAs(Paths.get("assets/barcode_stamped_sample.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
PDF 파일에 QR 코드를 삽입하세요
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.BarcodeEncoding;
import com.ironsoftware.ironpdf.stamp.BarcodeStamper;
import com.ironsoftware.ironpdf.stamp.HorizontalAlignment;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;
public class StampQrCodeExample {
public static void main(String[] args) {
try {
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
BarcodeStamper QRStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.QRCode);
QRStamp.setHeight(50);
QRStamp.setWidth(50);
QRStamp.setHorizontalAlignment(HorizontalAlignment.LEFT);
QRStamp.setVerticalAlignment(VerticalAlignment.BOTTOM);
pdf.applyStamp(QRStamp);
pdf.saveAs(Paths.get("assets/qrcode_stamped_sample.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.BarcodeEncoding;
import com.ironsoftware.ironpdf.stamp.BarcodeStamper;
import com.ironsoftware.ironpdf.stamp.HorizontalAlignment;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;
public class StampQrCodeExample {
public static void main(String[] args) {
try {
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
BarcodeStamper QRStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.QRCode);
QRStamp.setHeight(50);
QRStamp.setWidth(50);
QRStamp.setHorizontalAlignment(HorizontalAlignment.LEFT);
QRStamp.setVerticalAlignment(VerticalAlignment.BOTTOM);
pdf.applyStamp(QRStamp);
pdf.saveAs(Paths.get("assets/qrcode_stamped_sample.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
PDF에 워터마크 추가하기
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
public class AddWatermarkExample {
public static void main(String[] args) {
try {
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
String html = "<h1> Example Title <h1/>";
int watermarkOpacity = 30;
pdf.applyWatermark(html, watermarkOpacity);
pdf.saveAs(Paths.get("assets/watermarked_sample.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
public class AddWatermarkExample {
public static void main(String[] args) {
try {
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
String html = "<h1> Example Title <h1/>";
int watermarkOpacity = 30;
pdf.applyWatermark(html, watermarkOpacity);
pdf.saveAs(Paths.get("assets/watermarked_sample.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
PDF에서 양식 사용하기
IronPDF Java는 FormManager 클래스를 사용하여 PDF 문서의 폼 텍스트 필드에서 값을 설정하고 검색하는 간단하고 효율적인 방법을 제공합니다. 개발자는 setFieldValue 메서드를 호출하여 텍스트 필드 이름과 값을 제공할 수 있습니다.
해당 이름 또는 인덱스를 사용하여 FormManager의 FormField 객체 컬렉션을 통해 직접 폼 필드의 값을 검색할 수 있습니다. 이처럼 양식 필드에 대한 세밀한 제어 기능을 통해 동적이고 상호작용적인 PDF 양식을 손쉽게 작업할 수 있습니다.
양식 생성 및 편집
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import java.io.IOException;
import java.nio.file.Paths;
public class CreateAndEditFormsExample {
public static void main(String[] args) {
try {
// #1 Use Case: Create a PDF Form from HTML Form Markup
Path outputLocation = Paths.get("assets/BasicForm.pdf");
String formHTML = "<html>" +
"<body>" +
"<h2>Editable PDF Form</h2>" +
"<form>" +
"First name: <br> <input type='text' name='firstname' value=''> <br>" +
"Last name: <br> <input type='text' name='lastname' value=''>" +
"</form>" +
"</body>" +
"</html>";
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
renderOptions.setCreatePdfFormsFromHtml(true);
PdfDocument.renderHtmlAsPdf(formHTML, renderOptions).saveAs(outputLocation);
// #2 Use Case: Writing Values to the PDF Form
PdfDocument form = PdfDocument.fromFile(outputLocation);
// Set the value of the firstname input field.
form.getForm().setFieldValue("firstname", "Minnie");
// Set the value of the lastname input field.
form.getForm().setFieldValue("lastname", "Mouse");
// Save the changes to the PDF Form.
form.saveAs(Paths.get("assets/BasicForm_Filled.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import java.io.IOException;
import java.nio.file.Paths;
public class CreateAndEditFormsExample {
public static void main(String[] args) {
try {
// #1 Use Case: Create a PDF Form from HTML Form Markup
Path outputLocation = Paths.get("assets/BasicForm.pdf");
String formHTML = "<html>" +
"<body>" +
"<h2>Editable PDF Form</h2>" +
"<form>" +
"First name: <br> <input type='text' name='firstname' value=''> <br>" +
"Last name: <br> <input type='text' name='lastname' value=''>" +
"</form>" +
"</body>" +
"</html>";
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
renderOptions.setCreatePdfFormsFromHtml(true);
PdfDocument.renderHtmlAsPdf(formHTML, renderOptions).saveAs(outputLocation);
// #2 Use Case: Writing Values to the PDF Form
PdfDocument form = PdfDocument.fromFile(outputLocation);
// Set the value of the firstname input field.
form.getForm().setFieldValue("firstname", "Minnie");
// Set the value of the lastname input field.
form.getForm().setFieldValue("lastname", "Mouse");
// Save the changes to the PDF Form.
form.saveAs(Paths.get("assets/BasicForm_Filled.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
기존 양식 작성
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
public class FillExistingFormsExample {
public static void main(String[] args) {
try {
PdfDocument form = PdfDocument.fromFile("assets/pdfform.pdf");
// Set the value of the firstname input field.
form.getForm().setFieldValue("firstname", "Minnie");
// Set the value of the lastname input field.
form.getForm().setFieldValue("lastname", "Mouse");
// Save the changes to the PDF Form.
form.saveAs(Paths.get("assets/BasicForm_Filled.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
public class FillExistingFormsExample {
public static void main(String[] args) {
try {
PdfDocument form = PdfDocument.fromFile("assets/pdfform.pdf");
// Set the value of the firstname input field.
form.getForm().setFieldValue("firstname", "Minnie");
// Set the value of the lastname input field.
form.getForm().setFieldValue("lastname", "Mouse");
// Save the changes to the PDF Form.
form.saveAs(Paths.get("assets/BasicForm_Filled.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
인쇄용 PDF 파일을 보내주세요
IronPDF의 인쇄 방식을 사용하면 개발자가 애플리케이션에 PDF 인쇄 기능을 쉽게 통합 할 수 있습니다. [print](/java/object-reference/api/com/ironsoftware/ironpdf/PdfDocument.html#print()) 메서드를 호출하면 운영 체제의 인쇄 대화 상자가 열리며, 사용자가 프린터, 용지 크기 및 복사본 수와 같은 설정을 조정할 수 있는 옵션을 제공합니다.
import com.ironsoftware.ironpdf.PdfDocument;
import java.awt.print.PrinterException;
public class PrintPdfExample {
public static void main(String[] args) {
try {
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Created with IronPDF!</h1>");
pdf.print();
} catch (PrinterException exception) {
System.out.println("Failed to print PDF");
exception.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
import com.ironsoftware.ironpdf.PdfDocument;
import java.awt.print.PrinterException;
public class PrintPdfExample {
public static void main(String[] args) {
try {
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Created with IronPDF!</h1>");
pdf.print();
} catch (PrinterException exception) {
System.out.println("Failed to print PDF");
exception.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
결론
IronPDF 는 PDF 문서를 생성, 편집 및 조작하기 위한 다양한 기능을 제공하는 Java용 종합 PDF 라이브러리입니다. 이 소프트웨어는 텍스트 및 이미지 추출을 위한 강력한 방법을 제공하여 개발자가 PDF 콘텐츠에 접근하고 처리할 수 있도록 합니다. IronPDF PDF 메타데이터 및 보안 설정을 유연하게 사용자 지정할 수 있도록 지원하며, 예를 들어 PDF를 읽기 전용으로 만들거나 암호로 보호할 수 있습니다. 이 기술에는 PDF 파일을 압축하여 파일 크기를 줄이고 전송 효율을 향상시키는 방법이 포함되어 있습니다.
이 라이브러리를 사용하면 PDF 문서에 사용자 지정 머리글과 바닥글, 그리고 주석을 추가할 수 있습니다. 북마크 기능은 개발자가 PDF 내에서 쉽게 탐색할 수 있도록 북마크를 추가할 수 있게 해줍니다.
IronPDF 사용자가 구매 전에 기능과 성능을 테스트해 볼 수 있도록 무료 평가판 키를 제공합니다. IronPDF Java 라이선스는 $799에서 시작되며, PDF 파일을 안전하게 관리하려는 기업과 개인을 위한 비용 효율적인 솔루션을 제공합니다.
자주 묻는 질문
Java PDF 편집기 라이브러리의 주요 기능은 무엇입니까?
Java PDF 편집기 라이브러리는 서명, HTML 바닥글, 워터마크, 주석 추가를 포함하여 PDF를 편집하고 생성하는 데 필요한 다양한 도구를 제공합니다. 또한 PDF 병합 및 분할, 크기 및 방향 사용자 지정, PDF를 이미지로 변환하는 기능도 지원합니다.
PDF 라이브러리를 내 Java 프로젝트에 통합하려면 어떻게 해야 할까요?
IronPDF와 같은 PDF 라이브러리를 Java 프로젝트에 통합하려면 IronPDF 공식 사이트에서 라이브러리를 다운로드하고 프로젝트의 빌드 구성에 종속성으로 추가하세요.
Java에서 PDF 문서의 구조를 어떻게 수정할 수 있나요?
IronPDF를 사용하면 Java에서 PDF 문서의 구조를 수정할 수 있습니다. prependPdf , copyPages , removePages 와 같은 메서드를 활용하여 페이지를 추가, 복사 및 삭제할 수 있습니다.
PDF 파일에 사용자 지정 여백과 메타데이터를 설정할 수 있나요?
예, IronPDF는 MetadataManager 클래스를 사용하여 사용자 지정 여백을 설정하고 작성자 및 키워드를 포함한 PDF 메타데이터를 수정할 수 있도록 지원합니다.
Java를 사용하여 PDF 문서를 이미지 형식으로 변환할 수 있습니까?
IronPDF를 사용하면 toBufferedImages 메서드를 통해 PDF 페이지를 이미지 형식으로 변환할 수 있으며, 이 메서드에서 이미지 크기와 DPI를 정의할 수 있습니다.
PDF 파일에 사용자 지정 워터마크를 추가하려면 어떻게 해야 하나요?
PDF 파일에 사용자 지정 워터마크를 추가하려면 IronPDF의 applyWatermark 메서드를 사용하세요. HTML과 같은 워터마크 내용을 지정하고 투명도를 조정할 수 있습니다.
IronPDF는 PDF 문서에 암호 보호 기능을 지원합니까?
네, IronPDF는 비밀번호 보호 기능을 지원하여 무단 접근 및 변경을 방지함으로써 문서를 안전하게 보호할 수 있습니다.
Java에서 PDF 양식을 처리하는 데 사용할 수 있는 도구는 무엇입니까?
IronPDF는 PDF 양식을 생성, 편집 및 채우기 위한 FormManager 클래스를 제공합니다. 이 클래스를 통해 양식 필드의 값을 설정하고 검색할 수 있습니다.
PDF 문서에 디지털 서명을 사용하여 문서 보안을 어떻게 확보할 수 있나요?
IronPDF는 X509Certificate2 디지털 인증서를 사용하여 PDF 문서에 안전하게 서명할 수 있도록 지원하여 문서의 진위성을 보장하고 무단 변경을 방지합니다.
PDF 파일의 크기를 줄이기 위해 압축하는 것이 가능할까요?
IronPDF는 PDF 파일을 압축하는 방법을 포함하고 있어 문서 품질을 유지하면서 파일 크기를 줄이는 데 도움이 됩니다.




