【问题标题】:How To Return a Pdf view from Spring to angularjs如何将 Pdf 视图从 Spring 返回到 angularjs
【发布时间】:2018-01-19 12:16:29
【问题描述】:

我在 java 中使用 itext pdf 创建了一个带有数据库值的 pdf。现在我需要在我的 angularjs 中打开该 ModelAndView。

这是我的代码

Controller.js

$scope.strPdf=function strPdf(id){

$http.get(urlBase+"/stockTransferPdf/"+id).success(function(data){

    alert("success");


    })

}

controller.java

@RequestMapping(value = "/stockTransferPdf/{id}", method = RequestMethod.GET)
    public ModelAndView stockTranferPdfView(@PathVariable int id,HttpServletRequest request,HttpServletResponse response) {

        StockTransferRequest str=inventoryService.getStockTransferRequest(id);


        ModelAndView m = new ModelAndView("stockTransferPdfView");
        m.getModelMap().addAttribute("stockTransfer",str);



        return m;



    }

My Pdf Creator Class.java

package com.opine.manufacturing_erp.web.report;

import java.io.File;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.pdf.GrayColor;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.LineSeparator;
import com.opine.manufacturing_erp.web.model.StockTransferRequest;
import com.opine.manufacturing_erp.web.model.StockTransferRequestList;

public class stockTransferPdfView extends AbstractITextPdfView{

    @Override
    public void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer,
            HttpServletRequest request, HttpServletResponse response) throws Exception {

        try{

            String rootPath = getClass().getClassLoader().getResource("").getPath();

            System.out.println(rootPath);

            File file = new File(rootPath + File.separator +"itext-test.pdf");

            FileOutputStream fileout = new FileOutputStream(file);
            PdfWriter.getInstance(document, fileout);

            StockTransferRequest st=(StockTransferRequest) model.get("stockTransfer");


            document.open();
        Paragraph header = new Paragraph(
                new Chunk("TOBEN LOGISTICS SOLUTION PVT. LTD.", FontFactory.getFont(FontFactory.COURIER_BOLD, 12)));
        header.setAlignment(Element.ALIGN_CENTER);
        Paragraph adrs_line1 = new Paragraph(
                new Chunk("#31 B1, Hare Krishna Illam, First Floor,", FontFactory.getFont(FontFactory.HELVETICA, 10)));
        Paragraph adrs_line2 = new Paragraph(
                new Chunk("Thilagar Street, R.S.Puram, Coimbatore,", FontFactory.getFont(FontFactory.HELVETICA, 10)));
        Paragraph adrs_line3 = new Paragraph(
                new Chunk("Tamil Nadu - 641 002, INDIA", FontFactory.getFont(FontFactory.HELVETICA, 10)));
        adrs_line1.setAlignment(Element.ALIGN_CENTER);
        adrs_line2.setAlignment(Element.ALIGN_CENTER);
        adrs_line3.setAlignment(Element.ALIGN_CENTER);




        Paragraph date = new Paragraph(new Chunk("Print Date:"+new Date(), FontFactory.getFont(FontFactory.COURIER, 8)));
        date.setAlignment(Element.ALIGN_RIGHT);
        date.setSpacingAfter(1);

        LineSeparator lsp=new LineSeparator();
        Font font = FontFactory.getFont(FontFactory.COURIER_BOLD);
        font.setColor(BaseColor.WHITE);

        Font font1 = new Font(FontFamily.COURIER, 8, Font.NORMAL, GrayColor.BLACK);


        //String filename = getClass().getClassLoader().getResource("").getPath() + File.separator+"logo_log.png";


        Paragraph stock_transfer_table_heading = new Paragraph(
                new Chunk("Stock Transfer Details", FontFactory.getFont(FontFactory.HELVETICA, 10)));
        stock_transfer_table_heading.setAlignment(Element.ALIGN_LEFT);

        Paragraph stock_transfer_list_table_heading = new Paragraph(
                new Chunk("Stock Transfer List", FontFactory.getFont(FontFactory.HELVETICA, 10)));
        stock_transfer_list_table_heading.setAlignment(Element.ALIGN_LEFT);


        PdfPTable stock_transfer_table=getStockTransferDetails(st,font1);
        PdfPTable stock_transfer_list_table=getStockTransferListDetails(st,font1);

        document.setMargins(30, 20, 5, 5); // left, right, top/bottom margin
        document.newPage();
        /* Image image = Image.getInstance(filename);
            image.scaleAbsoluteHeight(50);
            image.scaleAbsoluteWidth((image.getWidth() * 50) / image.getHeight());
            image.setAbsolutePosition(25f, 780f);

            document.add(image);*/

            document.add(header);
            document.add(adrs_line1);
            document.add(adrs_line2);
            document.add(adrs_line3);
            document.add(Chunk.NEWLINE);
            document.add(date);
            document.add(Chunk.NEWLINE);

            document.add(stock_transfer_table_heading);
            document.add(Chunk.NEWLINE);
            document.add(stock_transfer_table);
            document.add(Chunk.NEWLINE);

            document.add(stock_transfer_list_table_heading);
            document.add(Chunk.NEWLINE);
            document.add(stock_transfer_list_table);
            document.add(Chunk.NEWLINE);

            document.close();

        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

    private PdfPTable getStockTransferDetails(StockTransferRequest str,Font font) {


        PdfPTable table= new PdfPTable(2);
        table.setWidthPercentage(100);

        com.itextpdf.text.List list = new com.itextpdf.text.List();
        list.add(new ListItem("Created Date",font));
        list.add(new ListItem("Source WareHouse ",font));
        list.add(new ListItem("Target WareHouse ",font));
        list.add(new ListItem("Total Packages ",font));
        list.add(new ListItem("Transfer Status ",font));

        com.itextpdf.text.List valueList = new com.itextpdf.text.List();

        valueList.add(new ListItem(dateToString(str.getCreatedDate()),font));
        valueList.add(new ListItem(str.getSourceWarehouse().getWarehouse_name(),font));
        valueList.add(new ListItem(str.getTargetWarehouse().getWarehouse_name(),font));
        valueList.add(new ListItem(String.valueOf(str.getTotal_packages()),font));
        valueList.add(new ListItem(str.getTransfer_status(),font));


        Phrase phraseShipper = new Phrase();
        phraseShipper.add(list);
        PdfPCell phraseCellShipper = new PdfPCell();
        phraseCellShipper.addElement(phraseShipper);

        // We add this phrase to a cell-Service info
        Phrase phraseService = new Phrase();
        phraseService.add(valueList);
        PdfPCell phraseCellService = new PdfPCell();
        phraseCellService.addElement(phraseService);


        table.addCell(phraseCellShipper);
        table.addCell(phraseCellService);


        return table;




    }
    private PdfPTable getStockTransferListDetails(StockTransferRequest str,Font font) {




        PdfPTable table = getPdfTable(getStockTransferListColumenList(), font);
        table.setWidthPercentage(100);

        for(StockTransferRequestList strqlist:str.getStockTransferRequestList()){

            table.addCell(new Phrase(strqlist.getItem().getProduct_name(),font));
            table.addCell(new Phrase(dateToString(strqlist.getCreatedDate()),font));
            table.addCell(new Phrase(String.valueOf(strqlist.getQuantity()),font));
            table.addCell(new Phrase(strqlist.getUom(),font));


        }

        return table;


    }



    private String[] getStockTransferListColumenList() {
        String[] stock_transferList = new String[] { "Product", "Created Date", "Quantity", "UOM"};

        return stock_transferList;

    }

    private String dateToString(Date date) {
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy ");
        return df.format(date);
    }


    private PdfPTable getPdfTable(String[] ColumnNames, Font font) {
        // Create Cargo Table
        PdfPTable table = new PdfPTable(ColumnNames.length);
        /*font.setColor(BaseColor.WHITE);*/
        table.setWidthPercentage(100.0f);

        // define table header cell
        PdfPCell cell1 = new PdfPCell();
        cell1.setBackgroundColor(BaseColor.GRAY);
        cell1.setPadding(5);

        // write table header
        for (String colmn : ColumnNames) {
            cell1.setPhrase(new Phrase(colmn, font));
            table.addCell(cell1);
        }

        return table;
    }

}

使用上面的代码,我可以创建一个包含数据库内容的 pdf 文件,但我需要显示 pdf 文件。我不知道该怎么做。

从过去的两天开始,我对此感到震惊。任何人都可以帮助我实现我的需要。

【问题讨论】:

  • 我希望您已经正确定义了视图解析器,并且您是否尝试过使用 $window.open 直接指向 url?
  • 在此处查看此示例:mkyong.com/spring-mvc/…
  • @Barath 如何在 $window.open() 中打开模型和视图
  • 只需在window.open函数中传递url即可打开PDF
  • @Barath pdf 存储在 web-inf/classs/ 文件夹中尝试打开它,但我不能

标签: java angularjs spring pdf


【解决方案1】:

在 Spring Controller 中,您的方法应该如下所示。

@RequestMapping(value = "createPdf", method = RequestMethod.GET, produces = "application/pdf")
public ResponseEntity<byte[]> createPdf(HttpServletResponse response) {

    response.setContentType("application/pdf");

    byte[] contents = // populate pdf data

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    headers.set("Content-Disposition", "inline");

    return new ResponseEntity<>(contents, headers, HttpStatus.OK);        
}

然后在 Angular JS 中。

$http({
    url: "url",
    method: 'GET',
    responseType: 'arraybuffer'
    })
    .then(({ data }) => {
        var file = new Blob([data], { type: 'application/pdf' });
        var fileURL = URL.createObjectURL(file);

        $window.open(fileURL);
    })

【讨论】:

  • Pdf 数据是数据库内容,那么我如何将其提供给 byte[] contents.my pdf 文件是在模型和视图中创建的
  • 如果可以将pdf数据作为Stringstr检索,则可以使用str.getBytes()
  • 我的pdf文件包含表格格式数据如何显示在同一个
  • 只是为了明确一点,pdf数据是保存在数据库中的,还是pdf是简单地使用buildPdfDocument()从数据库数据构造出来的?
  • pdf 是使用 itext pdf 中的 buildPdfDocument() 从数据库值简单构造的
猜你喜欢
  • 2016-01-08
  • 1970-01-01
  • 2016-04-16
  • 1970-01-01
  • 2015-10-08
  • 1970-01-01
  • 1970-01-01
  • 2011-09-27
  • 1970-01-01
相关资源
最近更新 更多