2

I create a pdf with databse values using itext pdf in java.Now i need to open that ModelAndView in my angularjs.

Here is my code

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;
    }

}

using the above code i can able to create a pdf file with database content but i need to display the pdf file. i don't know how to do this.

i am struck in this from past two days. Can any one help me to achieve my need.

6
  • I hope you have defined the view resolvers properly and have you tried using $window.open pointing to the url directly ? Commented Aug 11, 2017 at 6:28
  • see this example here : mkyong.com/spring-mvc/… Commented Aug 11, 2017 at 6:31
  • @Barath how to open a model and view in $window.open() Commented Aug 11, 2017 at 6:40
  • Just pass the url inside window.open function PDF will get opened Commented Aug 11, 2017 at 7:00
  • @Barath pdf is stored in web-inf/classs/ folder itried to open that but i can't Commented Aug 11, 2017 at 7:09

1 Answer 1

1

In Spring Controller your method should look like this.

@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);        
}

Then in 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);
    })
Sign up to request clarification or add additional context in comments.

10 Comments

Pdf Data's are database content then how can i give it to byte[] contents.my pdf file is created in model and view
If you can retrieve pdf data as a String str, you can use str.getBytes().
my pdf file contains table format data how to display in same
Just to make clear, pdf data is saved in the database, or pdf is simply constructed from database data using buildPdfDocument()?
pdf is simple constructed from database values using buildPdfDocument() in itext pdf
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.