【发布时间】:2019-11-12 10:42:59
【问题描述】:
我正在尝试从我的 Spring Boot 应用程序生成 PDF。我正在使用 itextpdf 和 pdfbox 。我在Optional<List<User>> bean 中获取所需的用户详细信息。如何将此 bean 转换/传递给仅接受字符串的 JsonParser?
这是我迄今为止尝试过的
控制器:-
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static javax.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM;
import static javax.ws.rs.core.Response.status;
import static org.apache.http.HttpStatus.SC_BAD_REQUEST;
import static org.apache.http.HttpStatus.SC_OK;
@Slf4j
@EnableLogging
@Path("/UserDetails")
public class UserDetails {
@GET
@Produces(APPLICATION_JSON)
public Response execute() throws WebApplicationException, FileNotFoundException, DocumentException {
Optional<List<User>> user = DAO.getUsers();
if (user.isPresent()) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse("Some String");
String prettyJsonString = gson.toJson(je);
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("myJSON.pdf"));
document.open();
Font font = FontFactory.getFont(FontFactory.COURIER, 16, BaseColor.BLACK);
Chunk chunk = new Chunk(prettyJsonString, font);
document.add(chunk);
document.close();
return status(SC_OK).entity(user).build();
} else {
return status(SC_BAD_REQUEST).entity(user).build();
}
}
}
【问题讨论】:
-
我没有看到任何 PDFBox 代码,那为什么是标签?
标签: spring-boot pdf itext pdfbox