
com.clusterra.pmbok.generate.pdf.PdfGeneratorServiceImpl Maven / Gradle / Ivy
/*
* Copyright (c) 2015.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Created by Liventsev Andrey. 03.01.14 21:19
package com.clusterra.pmbok.generate.pdf;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.xhtmlrenderer.layout.SharedContext;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
@Service
public class PdfGeneratorServiceImpl implements PdfGeneratorService {
@Autowired
private Resource defaultFontFile;
@Override
public byte[] generatePdfFromHtml(String html, Map resourceMap) {
ITextRenderer renderer = new ITextRenderer();
SharedContext sharedContext = renderer.getSharedContext();
ITextFontResolver resolver = renderer.getFontResolver();
try {
resolver.addFont(defaultFontFile.getURI().toString(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
} catch (Exception e) {
throw new RuntimeException(e);
}
// css
ResourceLoaderUserAgent callback = new ResourceLoaderUserAgent(renderer.getOutputDevice(), resourceMap);
callback.setSharedContext(sharedContext);
sharedContext.setUserAgentCallback(callback);
// images
sharedContext.setReplacedElementFactory(new ImageElementFactory(sharedContext.getReplacedElementFactory(), resourceMap));
renderer.setDocumentFromString(html);
renderer.layout();
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
renderer.createPDF(out);
} catch (DocumentException | IOException e) {
throw new RuntimeException(e);
}
byte[] bytes = out.toByteArray();
IOUtils.closeQuietly(out);
return bytes;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy