HTMLをPDFに変換する

HTML を PDF に変換する方法 | HTML を PDF にオンラインで変換

HTMLはWeb開発の主要なファイル形式で、最近のWebブラウザの大半はHTML仕様をサポートしています。プラットフォームに依存せず、どのオペレーティングシステムでも表示できますが、悪意のあるスクリプトの影響を受けやすく、インターネット上で簡単に共有できません。そのため、このような状況を避け、長期保存するために、WebページをPDF(Portable Document Format)として保存します。そこで、この記事では、Java REST APIを使用してHTMLをPDFに変換する手順について説明します。

HTML から PDF への変換 API

Aspose.HTML Cloud SDK for Java を使用すると、Java アプリケーション内で HTML 操作を実行できます。また、HTML を固定レイアウトのドキュメント形式 (PDF または XPS) に変換することもできます。変換を実行するには、クラウド ストレージからソース HTML (XHTMLMHTMLEPUBMarkdown) を読み込むか、Web ページの URL を指定します。SDK を使用するには、Maven ビルド プロジェクトの pom.xml に次の依存関係を追加して、aspose-html.jar をプロジェクトに追加できるようにします。

<repositories> 
    <repository>
        <id>aspose-cloud</id>
        <name>artifact.aspose-cloud-releases</name>
        <url>http://artifact.aspose.cloud/repo</url>
    </repository>   
</repositories>

<dependencies>
    <dependency>
        <groupId>com.aspose</groupId>
	<artifactId>aspose-html-cloud</artifactId>
	<version>20.7.0</version>
	<scope>compile</scope>
    </dependency>
</dependencies>

JavaでHTMLをPDFに変換する

Java アプリケーションで Web ページを PDF に変換するには、以下の手順に従ってください。

  • まず、Configuration.setAPPSID に対して詳細を指定する必要があります。
  • 次に、Configuration.setAPIKEY 情報を指定します。
  • 3番目に、setBasePath(..)の詳細を設定します。
  • 次に、setAuthPath(..) の詳細を指定する必要があります。
  • setUserAgent(…) を WebKit として設定します。
  • 私たち自身の支援のために、setDebug(..) を true に設定します。
  • API を使用すると、結果ファイルの余白の詳細を指定することもできます。
  • 次のステップは、入力 HTML ファイルを読み取って File インスタンスに読み込むことです。
  • ここで、RequestBody クラスのインスタンスを作成し、メディアを「multipart/form-data」として解析する必要があります。
  • ConversionApi クラスのオブジェクトを作成します。
  • ファイルをクラウド ストレージにアップロードするため、StorageApi のインスタンスも作成する必要があります。
  • ここで、PostConvertDocumentInRequestToPdf(..) を呼び出して変換プロセスを開始する必要があります。このメソッドは、入力ファイル名、結果ファイル名、結果ファイルの余白と寸法の詳細を引数として受け入れます。
  • 変換後、応答本体の生のバイトを含む結果が Stream オブジェクトに返されます。
  • ここで、成功した応答の逆シリアル化された応答本体を ResponseBody オブジェクトに取得する必要があります。
  • 結果のファイルをクラウド ストレージから ResponseBody オブジェクトにダウンロードします。
  • 最後に、カスタム メソッドを呼び出して、結果の PDF ドキュメントをローカル システム ドライブに保存します。
import com.aspose.html.api.ConversionApi;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Call;
import java.io.*;
public class conversionCode {
    public static void main(String[] args) {
    com.aspose.html.Configuration.setAPP_SID("c235e685-1aab-4cda-a95b-54afd63eb87f");
    com.aspose.html.Configuration.setAPI_KEY("b8da4ee37494f2ef8da3c727f3a0acb9");
    com.aspose.html.Configuration.setBasePath("https://api.aspose.cloud/v3.0");
    com.aspose.html.Configuration.setAuthPath("https://api.aspose.cloud/connect/token");
    com.aspose.html.Configuration.setUserAgent("WebKit");
    com.aspose.html.Configuration.setDebug(true);
		
    String name = "Simple.html";// inpit Document name.
		    	
    Integer width = 800; // Resulting image width.
    Integer height = 1000; // Resulting image height.
    Integer leftMargin = 10; // Left resulting image margin.
    Integer rightMargin = 10; // Right resulting image margin.
    Integer topMargin = 10; // Top resulting image margin.
    Integer bottomMargin = 10; // Bottom resulting image margin.
    String storage = null; // Name of the storage.
    File f = new File("/Users/nayyershahbaz/Documents/"+name);
    if(!f.exists()){
	System.out.println("file not found");
	}
    RequestBody requestBody = RequestBody.create( MediaType.parse("multipart/form-data"), f);
    MultipartBody.Part file = MultipartBody.Part.createFormData("file", f.getName(), requestBody);
				
    try {			
	ConversionApi api = new com.aspose.html.ApiClient().createService(ConversionApi.class);
	com.aspose.html.api.StorageApi storageApi = new com.aspose.html.ApiClient().createService(com.aspose.html.api.StorageApi.class);
		        
        Call<ResponseBody> call2 = api.PostConvertDocumentInRequestToPdf("resultantFile.pdf", file, width, height, leftMargin, rightMargin, topMargin, bottomMargin);
	retrofit2.Response<ResponseBody> res = call2.execute();
	ResponseBody resultant = res.body();
      	call2 = storageApi.downloadFile("resultantFile.pdf", null, storage);
      	checkAndSave(call2, "resultantFile.pdf");
        } catch (Exception e) {
	System.err.println("Exception during file processing...");
	e.printStackTrace();
	}
    } // main ends here
	
public static void checkAndSave(Call<ResponseBody> call, String fileName) throws IOException 
{
    retrofit2.Response<ResponseBody> res = call.execute();
    ResponseBody answer = res.body();
    //テストディレクトリに保存
    boolean result = saveToDisc(answer, fileName);
}
  
public static boolean saveToDisc(ResponseBody body, String fileName) 
{
    File savedFile = new File("/Users/nayyershahbaz/Documents/"+fileName);
    try (InputStream inputStream = body.byteStream();
    OutputStream outputStream = new FileOutputStream(savedFile))
    {
    	byte[] fileReader = new byte[4096];
	long fileSizeDownloaded = 0;

	while (true) {
	int read = inputStream.read(fileReader);
	if (read == -1) break;

	outputStream.write(fileReader, 0, read);
	fileSizeDownloaded += read;
	}
	outputStream.flush();
	return true;

    } catch (Exception e) {
	e.printStackTrace();
	return false;
    }
} // saveToDisc ends here

}

結論

この記事では、Java SDK を使用して Web ページを PDF に変換する手順について説明しました。コード行数が少なく、完全な HTML が完全な忠実度で PDF 形式にレンダリングされることがわかりました。PDF 形式以外にも、API を使用すると、HTML から JPG、HTML から PNG、HTML から TIFF、HTML から BMP、HTML から GIF への変換操作も実行できます。同様に、同じ API を使用して、Markdown ファイルを HTML に変換したり、MHTML を HTML 形式に変換したりできます。

APIの使用中に問題が発生した場合は、無料製品サポートフォーラムからお気軽にお問い合わせください。

関連リンク

詳細については、以下のリンクをご覧ください。