我正在尝试从Spring引导应用程序生成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();
}
}
}