刘光辉
8 小时以前 06f314545ac3514d7ce28939920866ae8188d31c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package jnpf.bizcommon.onlyoffice.service.impl;
 
import jnpf.bizcommon.onlyoffice.entity.OnlyOfficeProperties;
import jnpf.exception.DataException;
import lombok.RequiredArgsConstructor;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.springframework.stereotype.Component;
 
import java.io.ByteArrayOutputStream;
import java.util.List;
 
@Component
@RequiredArgsConstructor
public class OnlyOfficeDmsPrintPdfMerger {
    private final OnlyOfficeProperties properties;
 
    public byte[] merge(List<byte[]> sources) {
        if (sources == null || sources.isEmpty()) {
            throw new DataException("批量打印结果为空");
        }
        if (sources.size() == 1) {
            return sources.get(0);
        }
 
        OnlyOfficeProperties.DmsPrint limits = properties.getDmsPrint();
        long totalBytes = 0;
        int totalPages = 0;
        try (PDDocument merged = new PDDocument();
             ByteArrayOutputStream output = new ByteArrayOutputStream()) {
            for (byte[] sourceBytes : sources) {
                if (sourceBytes == null || sourceBytes.length == 0
                        || totalBytes > limits.getMaxPdfBytes() - sourceBytes.length) {
                    throw new DataException("批量打印 PDF 超过系统大小限制");
                }
                totalBytes += sourceBytes.length;
                try (PDDocument source = Loader.loadPDF(sourceBytes)) {
                    if (totalPages > limits.getMaxPages() - source.getNumberOfPages()) {
                        throw new DataException("批量打印 PDF 页数超过系统限制");
                    }
                    totalPages += source.getNumberOfPages();
                    for (PDPage page : source.getPages()) {
                        merged.importPage(page);
                    }
                }
            }
            merged.save(output);
            if (output.size() > limits.getMaxPdfBytes()) {
                throw new DataException("批量打印 PDF 超过系统大小限制");
            }
            return output.toByteArray();
        } catch (DataException exception) {
            throw exception;
        } catch (Exception exception) {
            throw new DataException("合并批量打印 PDF 失败");
        }
    }
}