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 失败");
|
}
|
}
|
}
|