푸터 콘텐츠로 바로가기
JAVA용 IRONPDF 사용

Java에서 바이트 배열을 PDF로 변환하는 방법

This article will discuss how to convert a byte array to a PDF in Java and use the IronPDF Java PDF library.

IronPDF: Java PDF Library

IronPDF Java PDF Library is a popular Java library for generating, reading, and manipulating PDF documents. It is developed by Iron Software, a software development company that specializes in developing productivity libraries and tools.

IronPDF provides a range of features for creating and manipulating PDFs. This includes the ability to:

  1. Convert HTML content to PDF and plain text documents to PDF, to add text and images to PDFs,
  2. Create and fill PDF forms with ease,
  3. Merge multiple PDFs and split PDFs into separate documents,
  4. and more.

The library also includes support for encryption to protect your PDFs and digital signatures for document security.

IronPDF uses a simple and intuitive API that makes it easy for developers of all levels to use. Additionally, IronPDF offers comprehensive documentation, code samples to get you started, and support to help developers get started with the library quickly.

Let's explore how to use IronPDF to convert a byte array to a PDF file.

Install IronPDF Java library in Maven Project

To install the IronPDF Java library in a Maven project, follow these steps:

  1. Open your project's pom.xml file and locate the <dependencies> tag.
  2. Add the following XML code to the <dependencies> tag to add IronPDF for Java as a dependency:

    XML
  3. Add the following XML code to the <dependencies> tag to add the SLF4J Simple logger, which IronPDF for Java uses to log status messages to the console.

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-simple</artifactId>
      <version>2.0.3</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-simple</artifactId>
      <version>2.0.3</version>
    </dependency>
    XML
  4. Save the pom.xml file.

After you save the pom.xml file, Maven will automatically download and install the IronPDF for Java library and the SLF4J Simple logger. You can then use the IronPDF library in your Java code.

Note that the version number used in the XML code above may not be the latest version available when you install the library. You should always use the latest library version for bug fixes and new features.

Sample Code

Here is the sample code to convert the byte array to a PDF file:

package IronPDF.ironpdf_java;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import com.ironsoftware.ironpdf.*;

public class Test {
    public static void main(String[] args) throws IOException {
        // Define the byte array representing the ASCII characters
        byte[] byteArray = {84, 104, 105, 115, 32, 105, 115, 32, 98, 121, 116, 101, 32, 97, 114, 114, 97, 121};

        // Convert the byte array to a string using US_ASCII encoding
        String data = new String(byteArray, StandardCharsets.US_ASCII);

        // Embed the string data in HTML format
        String HTML = "<h1>" + data + "</h1>";

        // Apply your license key for IronPDF
        License.setLicenseKey("YOUR-LICENSE-KEY");

        // Render the HTML as a PDF document using IronPDF
        PdfDocument pdf = PdfDocument.renderHtmlAsPdf(HTML);

        // Save the PDF file to a specified location
        pdf.saveAs("C:\\byteToPdf.pdf");
    }
}
package IronPDF.ironpdf_java;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import com.ironsoftware.ironpdf.*;

public class Test {
    public static void main(String[] args) throws IOException {
        // Define the byte array representing the ASCII characters
        byte[] byteArray = {84, 104, 105, 115, 32, 105, 115, 32, 98, 121, 116, 101, 32, 97, 114, 114, 97, 121};

        // Convert the byte array to a string using US_ASCII encoding
        String data = new String(byteArray, StandardCharsets.US_ASCII);

        // Embed the string data in HTML format
        String HTML = "<h1>" + data + "</h1>";

        // Apply your license key for IronPDF
        License.setLicenseKey("YOUR-LICENSE-KEY");

        // Render the HTML as a PDF document using IronPDF
        PdfDocument pdf = PdfDocument.renderHtmlAsPdf(HTML);

        // Save the PDF file to a specified location
        pdf.saveAs("C:\\byteToPdf.pdf");
    }
}
JAVA

Explanation of the Code

Step 1: The provided code demonstrates converting a byte array to a PDF using IronPDF. At the beginning of the code, the necessary Java libraries are imported. This includes the IronPDF library and the StandardCharsets library.

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import com.ironsoftware.ironpdf.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import com.ironsoftware.ironpdf.*;
JAVA

Step 2: The first step is to create a byte array containing the data to be converted. In this case, the byte array contains the string "This is byte array" in ASCII format.

byte[] byteArray = {84, 104, 105, 115, 32, 105, 115, 32, 98, 121, 116, 101, 32, 97, 114, 114, 97, 121};
byte[] byteArray = {84, 104, 105, 115, 32, 105, 115, 32, 98, 121, 116, 101, 32, 97, 114, 114, 97, 121};
JAVA

Step 3: Next, the byte array is converted to a string using the US_ASCII character encoding. This is done by calling the String constructor and passing the byte array and the appropriate character encoding as parameters.

String data = new String(byteArray, StandardCharsets.US_ASCII);
String data = new String(byteArray, StandardCharsets.US_ASCII);
JAVA

Step 4: An HTML string is then created using the data from the byte array. The string is wrapped in an H1 tag to make it stand out in the PDF.

String HTML = "<h1>" + data + "</h1>";
String HTML = "<h1>" + data + "</h1>";
JAVA

Step 5: After creating the HTML string, the IronPDF library renders the HTML as a PDF. The PDF is then saved to a file on the local disk with the given filename.

// Apply your license key
License.setLicenseKey("YOUR-LICENSE-KEY");
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(HTML);
pdf.saveAs("C:\\byteToPdf.pdf");
// Apply your license key
License.setLicenseKey("YOUR-LICENSE-KEY");
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(HTML);
pdf.saveAs("C:\\byteToPdf.pdf");
JAVA

Output File

Here is the output PDF document generated by IronPDF Java PDF Library:

How to Convert Byte Array to PDF in Java, Figure 1: Output PDF generated by IronPDF Java Output PDF generated by IronPDF Java

Conclusion

By following the steps outlined in this article, you can convert a byte array to a PDF file and save it on your local disk.

IronPDF is a commercial library and requires a license purchase for production environments. The cost for an IronPDF license starts at $799 per developer per year; there are other license options available depending on the number of developers and deployment servers.

However, IronPDF offers a free trial of IronPDF that allows developers to test the library and evaluate its features and capabilities. This free trial includes full access to all features of the library. Developers can use it to convert up to 20 pages of a PDF document.

자주 묻는 질문

Java에서 바이트 배열을 PDF로 변환하려면 어떻게 해야 하나요?

IronPDF Java 라이브러리를 사용하여 바이트 배열을 PDF로 변환하려면 먼저 바이트 배열을 ASCII 문자로 변환하고 HTML 마크업에 포함시킵니다. 그런 다음 renderHtmlAsPdf 메서드를 사용하여 HTML을 PDF 문서로 변환합니다.

Maven 프로젝트에 PDF 라이브러리를 설치하는 단계는 무엇인가요?

Maven 프로젝트에 IronPDF를 설치하려면 pom.xml 파일의 <dependencies< 섹션에 IronPDF 종속성을 추가하세요. 또한 SLF4J Simple 로거 종속성을 포함하세요. 파일을 저장하면 Maven이 자동으로 라이브러리를 다운로드하고 설치합니다.

Java PDF 라이브러리에 대한 무료 평가판이 있나요?

예, IronPDF는 개발자가 구매하기 전에 최대 20페이지의 PDF 문서를 변환하는 등의 기능을 테스트할 수 있는 무료 평가판을 제공합니다.

Java 라이브러리를 사용하여 HTML 콘텐츠를 PDF로 변환할 수 있나요?

예, IronPDF는 HTML 콘텐츠를 PDF 문서로 변환하는 기능을 제공합니다. 또한 PDF에 텍스트 및 이미지 추가, 양식 생성 및 채우기 등의 기능도 제공합니다.

Java용 IronPDF에서 라이선스 키를 적용하려면 어떻게 해야 하나요?

Java 코드에서 License.setLicenseKey 메서드를 사용하여 IronPDF에 라이선스 키를 적용하면 라이브러리를 프로덕션용으로 사용할 수 있도록 인증할 수 있습니다.

Java용 IronPDF의 주요 기능은 무엇인가요?

IronPDF는 간단한 API를 통해 HTML을 PDF로 변환, 양식 생성 및 채우기, PDF 병합 및 분할, 보안을 위한 암호화 및 디지털 서명 기능을 제공합니다.

Java PDF 라이브러리에서 로거의 역할은 무엇인가요?

Java용 IronPDF에서 SLF4J Simple 로거는 상태 메시지를 콘솔에 기록하여 개발자가 애플리케이션을 디버깅하고 모니터링하는 데 도움을 줍니다.

IronPDF에 대한 문서와 코드 샘플은 어디에서 찾을 수 있나요?

IronPDF 문서와 코드 샘플은 IronPDF 웹사이트에서 확인할 수 있으며, 개발자가 효율적으로 시작하는 데 도움이 되는 포괄적인 지침과 예제를 제공합니다.

Java용 IronPDF의 라이선스 옵션은 무엇인가요?

IronPDF는 개발자 수와 배포 서버에 따라 다양한 라이선스 옵션을 제공하는 상용 라이브러리입니다. 라이선스는 개발자당 연간 특정 비용으로 시작됩니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.