ソースを参照

api-export-pdf

new-feature
Viet.LeQ2 1年前
コミット
1d624f0e67
7個のファイルの変更283行の追加1行の削除
  1. +3
    -0
      src/main/java/vn/azteam/tpf/service/TBCodeDetailsService.java
  2. +2
    -0
      src/main/java/vn/azteam/tpf/service/TBExampleStampService.java
  3. +85
    -0
      src/main/java/vn/azteam/tpf/service/impl/CustomElementFactoryImpl.java
  4. +136
    -1
      src/main/java/vn/azteam/tpf/service/impl/TBCodeDetailsImpl.java
  5. +15
    -0
      src/main/java/vn/azteam/tpf/service/impl/TBExampleStampServiceImpl.java
  6. +28
    -0
      src/main/java/vn/azteam/tpf/web/rest/TBCodeDetailsResource.java
  7. +14
    -0
      src/main/resources/html/template.html

+ 3
- 0
src/main/java/vn/azteam/tpf/service/TBCodeDetailsService.java ファイルの表示

@@ -13,6 +13,9 @@ import java.util.Optional;
*/

public interface TBCodeDetailsService {

byte[] exportPdfInfoTBCodeDetail(Long tbCodeDetailId);

TBCodeDetailsDTO save(TBCodeDetailsDTO tBCodeDetailsDTO);

List<TBCodeDetailsDTO> saveAll(List<TBCodeDetailsCreationDTO> tBCodeDetailsDTOs);

+ 2
- 0
src/main/java/vn/azteam/tpf/service/TBExampleStampService.java ファイルの表示

@@ -4,4 +4,6 @@ import vn.azteam.tpf.service.dto.TBExampleStampDTO;

public interface TBExampleStampService {
TBExampleStampDTO save(TBExampleStampDTO tBExampleStampDTO);

TBExampleStampDTO findById(Long id);
}

+ 85
- 0
src/main/java/vn/azteam/tpf/service/impl/CustomElementFactoryImpl.java ファイルの表示

@@ -0,0 +1,85 @@
package vn.azteam.tpf.service.impl;

import com.lowagie.text.Image;
import org.w3c.dom.Element;
import org.xhtmlrenderer.extend.FSImage;
import org.xhtmlrenderer.extend.ReplacedElement;
import org.xhtmlrenderer.extend.ReplacedElementFactory;
import org.xhtmlrenderer.extend.UserAgentCallback;
import org.xhtmlrenderer.layout.LayoutContext;
import org.xhtmlrenderer.pdf.ITextFSImage;
import org.xhtmlrenderer.pdf.ITextImageElement;
import org.xhtmlrenderer.render.BlockBox;
import org.xhtmlrenderer.simple.extend.FormSubmissionListener;

public class CustomElementFactoryImpl implements ReplacedElementFactory {

private final byte[] backGroundImage;

private final byte[] barCodeImage;


public CustomElementFactoryImpl(byte[] backGroundImage, byte[] barCodeImage) {
this.backGroundImage = backGroundImage;
this.barCodeImage = barCodeImage;
}

@Override
public ReplacedElement createReplacedElement(LayoutContext lc, BlockBox box, UserAgentCallback uac, int cssWidth, int cssHeight) {
Element e = box.getElement();
String nodeName = e.getNodeName();
if (nodeName.equals("img") && e.getAttribute("class").equals("background-image")) {
//e.setAttribute("style", "position: relative; width: 1000px; width: 1000px;");
//String imagePath = e.getAttribute("src");
try {

//InputStream input = new FileInputStream("src/main/resources/html/" + imagePath);
//byte[] bytes = IOUtils.toByteArray(input);
Image image = Image.getInstance(backGroundImage);
FSImage fsImage = new ITextFSImage(image);
if (cssWidth != -1 || cssHeight != -1) {
fsImage.scale(cssWidth, cssHeight);
} else {
fsImage.scale(2000, 1000);
}
return new ITextImageElement(fsImage);
} catch (Exception e1) {
e1.printStackTrace();
}
}

if (nodeName.equals("img") && e.getAttribute("class").equals("foreground-image")) {
//e.setAttribute("style", "position: absolute; width: 100px; height: 100px; top: 50px; left: 50px;");
//String imagePath = e.getAttribute("src");
try {

//InputStream input = new FileInputStream("src/main/resources/html/" + imagePath);
//byte[] bytes = IOUtils.toByteArray(input);
Image image = Image.getInstance(barCodeImage);
FSImage fsImage = new ITextFSImage(image);
if (cssWidth != -1 || cssHeight != -1) {
fsImage.scale(cssWidth, cssHeight);
} else {
fsImage.scale(2000, 1000);
}
return new ITextImageElement(fsImage);
} catch (Exception e1) {
e1.printStackTrace();
}
}

return null;
}

@Override
public void reset() {
}

@Override
public void remove(Element e) {
}

@Override
public void setFormSubmissionListener(FormSubmissionListener listener) {
}
}

+ 136
- 1
src/main/java/vn/azteam/tpf/service/impl/TBCodeDetailsImpl.java ファイルの表示

@@ -1,11 +1,22 @@
package vn.azteam.tpf.service.impl;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import io.github.jhipster.service.filter.LongFilter;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.dom4j.DocumentException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.xhtmlrenderer.layout.SharedContext;
import org.xhtmlrenderer.pdf.ITextRenderer;
import vn.azteam.tpf.domain.TBCode;
import vn.azteam.tpf.domain.TBCodeDetails;
import vn.azteam.tpf.domain.TBCodeStatusEnum;
@@ -19,6 +30,11 @@ import vn.azteam.tpf.service.mapper.TBCropMapper;
import vn.azteam.tpf.service.util.UserRoleUtil;
import vn.azteam.tpf.web.rest.errors.BadRequestAlertException;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
@@ -33,12 +49,16 @@ import java.util.stream.Collectors;
@Service
@Transactional
public class TBCodeDetailsImpl implements TBCodeDetailsService {

private static final String HTML_INPUT = "src/main/resources/html/template.html";
private final Logger log = LoggerFactory.getLogger(TBCodeDetailsImpl.class);

private static final String ENTITY_NAME = "tBCrop";

private final TBCodeDetailsRepository tbCodeDetailsRepository;

private final TBExampleStampService tbExampleStampService;

private final TBCodeDetailsMapper tBCodeDetailsMapper;

private final TBDetailUserRepository tBDetailUserRepository;
@@ -55,18 +75,22 @@ public class TBCodeDetailsImpl implements TBCodeDetailsService {

private final TBCropMapper tbCropMapper;

private final FileStorageService fileStorageService;

private final TBCodeDetailsSearchRepository tBCodeDetailsSearchRepository;

public TBCodeDetailsImpl(TBCodeDetailsRepository tbCodeDetailsRepository,
TBCodeDetailsMapper tBCodeDetailsMapper,
TBExampleStampService tbExampleStampService, TBCodeDetailsMapper tBCodeDetailsMapper,
TBDetailUserRepository tBDetailUserRepository,
UserService userService,
UserRoleUtil userRoleUtil,
TBActivityQueryService tBActivityQueryService, TBCropService tbCropService,
TBCropQueryService tBCropQueryService,
TBCropMapper tbCropMapper,
FileStorageService fileStorageService,
TBCodeDetailsSearchRepository tBCodeDetailsSearchRepository) {
this.tbCodeDetailsRepository = tbCodeDetailsRepository;
this.tbExampleStampService = tbExampleStampService;
this.tBCodeDetailsMapper = tBCodeDetailsMapper;
this.tBDetailUserRepository = tBDetailUserRepository;
this.userService = userService;
@@ -75,6 +99,7 @@ public class TBCodeDetailsImpl implements TBCodeDetailsService {
this.tbCropService = tbCropService;
this.tBCropQueryService = tBCropQueryService;
this.tbCropMapper = tbCropMapper;
this.fileStorageService = fileStorageService;
this.tBCodeDetailsSearchRepository = tBCodeDetailsSearchRepository;
}

@@ -276,4 +301,114 @@ public class TBCodeDetailsImpl implements TBCodeDetailsService {
throw new RuntimeException();
}
}

public byte[] exportPdfInfoTBCodeDetail(Long tbCodeDetailId) {
try {
Optional<TBCodeDetails> tbCodeDetailsOptional = tbCodeDetailsRepository.findById(tbCodeDetailId);
if (!tbCodeDetailsOptional.isPresent()) {
throw new BadRequestAlertException("1047", "TB CodeDetail export could found", "1047");
}

log.info("exportInfoTBCode: start query");
if (tbCodeDetailsOptional.isPresent()) {
TBCodeDetails tbCodeDetails = tbCodeDetailsOptional.get();
if (tbCodeDetails.getTbCode().getTbExampleStampId() != null) {
TBExampleStampDTO exampleStampDTO = tbExampleStampService.findById(tbCodeDetails.getTbCode().getTbExampleStampId());

return this.exportPdf(exampleStampDTO.getExampleStampImage(),
tbCodeDetails.getCode(), exampleStampDTO.getWidth(), exampleStampDTO.getHeight(),
exampleStampDTO.getX(), exampleStampDTO.getY());
}
}
} catch (Exception exception) {
log.error("exportInfoCampaignCalling exception", exception);
}
return new byte[0];
}

private static void xhtmlToPdf(Document xhtml, ByteArrayOutputStream byteOutputStream,
byte[] background, byte[] barCode, Integer width, Integer height,
Integer x, Integer y) throws Exception {
try (OutputStream outputStream = byteOutputStream) {
ITextRenderer renderer = new ITextRenderer();
SharedContext sharedContext = renderer.getSharedContext();
sharedContext.setPrint(true);
sharedContext.setInteractive(false);
sharedContext.setReplacedElementFactory(new CustomElementFactoryImpl(background, barCode));
String widthValue = width != null ? width.toString() + "px" : "302px";
String heightValue = height != null ? height.toString() + "px" : "302px";
String xValue = x != null ? x.toString() + "px" : "50px";
String yValue = y != null ? y.toString() + "px" : "51px";
renderer.setDocumentFromString(xhtml.html().replace("300px", widthValue)
.replace("301px", heightValue).replace("50px", xValue)
.replace("51px", yValue));
renderer.layout();
renderer.createPDF(outputStream);
}
}

public static byte[] readFileToByteArray(File file) {
byte[] byteArray = null;
try (FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream()) {

byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}

byteArray = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return byteArray;
}

private void generateHtmlToPdf(ByteArrayOutputStream byteOutputStream,
byte[] background, byte[] barCode,
Integer width, Integer height,
Integer x, Integer y) throws Exception {
File inputHTML = new File(HTML_INPUT);
Document inputHtml = createWellFormedHtml(inputHTML);
log.info("generateHtmlToPdf");
xhtmlToPdf(inputHtml, byteOutputStream, background, barCode, width, height, x, y);
}

private static Document createWellFormedHtml(File inputHTML) throws IOException {
Document document = Jsoup.parse(inputHTML, "UTF-8");
document.outputSettings()
.syntax(Document.OutputSettings.Syntax.xml);
return document;
}


public byte[] exportPdf(String image, String tbCodeDetailValue, Integer width, Integer height,
Integer x, Integer y) throws IOException,
DocumentException, WriterException {
log.info("exportPdf");
ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
try {

ByteArrayOutputStream byteArrayOutputStreamBarCode = new ByteArrayOutputStream();
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix matrix = qrCodeWriter.encode(tbCodeDetailValue, BarcodeFormat.QR_CODE,
200, 200);
ImageIO.write(MatrixToImageWriter.toBufferedImage(matrix), "jpg", byteArrayOutputStreamBarCode);

File backgroundImage = fileStorageService.loadFileAsResource("EXAMPLE_STAMP",
image.replace("EXAMPLE_STAMP/", "")).getFile();
log.info("generateHtmlToPdf");
generateHtmlToPdf(byteOutputStream,
readFileToByteArray(backgroundImage), byteArrayOutputStreamBarCode.toByteArray(),
width, height, x, y);

} catch (Exception e) {
log.info("generateHtmlToPdf Exception");
throw new RuntimeException(e);
}
return byteOutputStream.toByteArray();
}


}

+ 15
- 0
src/main/java/vn/azteam/tpf/service/impl/TBExampleStampServiceImpl.java ファイルの表示

@@ -10,6 +10,8 @@ import vn.azteam.tpf.service.TBExampleStampService;
import vn.azteam.tpf.service.dto.TBExampleStampDTO;
import vn.azteam.tpf.service.mapper.TBExampleStampMapper;

import java.util.Optional;

@Service
@Transactional
public class TBExampleStampServiceImpl implements TBExampleStampService {
@@ -34,4 +36,17 @@ public class TBExampleStampServiceImpl implements TBExampleStampService {
tbExampleStamp = tbExampleStampRepository.save(tbExampleStamp);
return tBExampleStampMapper.toDto(tbExampleStamp);
}

@Override
public TBExampleStampDTO findById(Long id) {
log.debug("Request to find TBExampleStampDTO by id : {}", id);
if (id == null) {
return new TBExampleStampDTO();
}
Optional<TBExampleStamp> tBExampleStampOptional = tbExampleStampRepository.findById(id);
if (tBExampleStampOptional.isPresent()) {
return tBExampleStampMapper.toDto(tBExampleStampOptional.get());
}
return new TBExampleStampDTO();
}
}

+ 28
- 0
src/main/java/vn/azteam/tpf/web/rest/TBCodeDetailsResource.java ファイルの表示

@@ -5,6 +5,9 @@ import io.github.jhipster.web.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import vn.azteam.tpf.domain.TBCodeStatusEnum;
@@ -15,6 +18,7 @@ import vn.azteam.tpf.service.dto.TBCodeDetailsDTO;
import vn.azteam.tpf.service.dto.UserDTO;
import vn.azteam.tpf.web.rest.errors.BadRequestAlertException;

import java.io.ByteArrayInputStream;
import java.time.Instant;
import java.util.Optional;

@@ -81,4 +85,28 @@ public class TBCodeDetailsResource {
// }
return ResponseUtil.wrapOrNotFound(tBCodeUpdated);
}

@GetMapping(value = "/tb-code-details/export-pdf/{id}")
public ResponseEntity<InputStreamResource> exportTbCode(
@PathVariable Long id) {
try {
log.info("REST request to exportTbCodeDetail : {}", id);
// if (StringUtils.isBlank(tbCodeValue)) {
// throw new BadRequestAlertException("1047", "TB Code export could not empty", "1047");
// }

byte[] out = tBCodeDetailsService.exportPdfInfoTBCodeDetail(id);

String fileName = "Export_tb_code_detail_pdf" + id + ".pdf";
InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(out));
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename= " + fileName)
.contentLength(out.length)
.contentType(MediaType.parseMediaType("application/pdf"))
.body(resource);
} catch (Exception e) {
log.info("REST request to exportTbCodeDetail error id : {}", id);
throw e;
}
}
}

+ 14
- 0
src/main/resources/html/template.html ファイルの表示

@@ -0,0 +1,14 @@
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<img src="background-image.jpg" alt="Background Image" style="position:relative;width: 300px;height: 301px;" class="background-image">
<img src="foreground-image.png" alt="Foreground Image" style="position: absolute; width: 100px; height: 100px; top: 50px; left: 51px;" class="foreground-image">
</div>
</body>
</html>




読み込み中…
キャンセル
保存