【问题标题】:Easiest method to convert JSON to PDF in java?在java中将JSON转换为PDF的最简单方法?
【发布时间】:2019-08-14 08:35:44
【问题描述】:

我使用 Java Spring Boot 框架,我需要将我的 Json 转换为 PDF。问题是 PDF 中的所有文本都写在一行中,这意味着换行符不起作用。结果,我得到一个 PDF,其中第一行是空白或空文件。

 @GetMapping("/pdf/{Id}")
    @Secured({"ROLE_ADMIN", "ROLE_OPERATOR", "ROLE_GUEST"})
    public ResponseEntity<PDDocument> findOnePdfByIdJob(@PathVariable("Id") Long id) throws DocumentException, IOException {
        Job job = jobService.findById(id);

        if (job == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonInString = objectMapper.writeValueAsString(job);

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        JsonParser jp = new JsonParser();
        JsonElement je = jp.parse(jsonInString);
        String prettyJsonString = gson.toJson(je);


        PDDocument document = new PDDocument();
        PDPage page = new PDPage();
        document.addPage(page);

        PDPageContentStream contentStream = new PDPageContentStream(document, page);

        contentStream.setFont(PDType1Font.COURIER, 12);
        contentStream.beginText();
        contentStream.showText(jsonInString);
        contentStream.endText();
        contentStream.close();

        document.save("pdfBoxHelloWorld.pdf");
        document.close();

        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(document);
    }

因此,我得到了一个 PDF,其中所有内容都写在一行中。也就是无法读取文本....第一行变成了空行。

【问题讨论】:

    标签: java json spring spring-boot pdf


    【解决方案1】:

    如果您已经使用Jackson 的ObjectMapper,则不需要使用Gson。只需启用SerializationFeature.INDENT_OUTPUT 功能,ObjectMapper 也会生成漂亮的JSON。此外,您需要在行上拆分JSON,并使用PDPageContentStream 中的newLine 方法逐行添加每一行。

    简单的应用:

    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.SerializationFeature;
    import com.fasterxml.jackson.databind.type.MapType;
    import org.apache.pdfbox.pdmodel.PDDocument;
    import org.apache.pdfbox.pdmodel.PDPage;
    import org.apache.pdfbox.pdmodel.PDPageContentStream;
    import org.apache.pdfbox.pdmodel.font.PDType1Font;
    
    import java.io.File;
    import java.util.Map;
    
    public class PdfApp {
    
        public static void main(String[] args) throws Exception {
            File jsonFile = new File("./resource/test.json").getAbsoluteFile();
    
            ObjectMapper mapper = new ObjectMapper();
            // enable pretty printing
            mapper.enable(SerializationFeature.INDENT_OUTPUT);
    
            // read map from file
            MapType mapType = mapper.getTypeFactory().constructMapType(Map.class, String.class, Object.class);
            Map<String, Object> map = mapper.readValue(jsonFile, mapType);
    
            // generate pretty JSON from map
            String json = mapper.writeValueAsString(map);
            // split by system new lines
            String[] strings = json.split(System.lineSeparator());
    
            PDDocument document = new PDDocument();
            PDPage page = new PDPage();
            document.addPage(page);
    
            PDPageContentStream contentStream = new PDPageContentStream(document, page);
    
            contentStream.setFont(PDType1Font.COURIER, 12);
            contentStream.beginText();
            contentStream.setLeading(14.5f);
            contentStream.newLineAtOffset(25, 725);
            for (String string : strings) {
                contentStream.showText(string);
                // add line manually
                contentStream.newLine();
            }
            contentStream.endText();
            contentStream.close();
    
            document.save("pdfBoxHelloWorld.pdf");
            document.close();
        }
    }
    

    生成PDF 文件,内容如下:

    另见:

    【讨论】:

    • 谢谢,但是当我尝试使用此示例时,如果我理解正确,它找不到其中一种字体:2019-03-23 19:48:30.701 ERROR 7700 --- [nio-8443 -exec-2] oappfont.FileSystemFontProvider : 无法加载字体文件:C:\Windows\FONTS\mstmc.ttf 当我调试一个程序崩溃就行了:contentStream.beginText();
    猜你喜欢
    • 2012-09-02
    • 2011-10-08
    • 2017-06-18
    • 2010-11-28
    • 2014-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多