How To Download A Pdf File In Angular 2
Today, I want to talk about the second method that exports data with a pdf file in Angular 2. We can do it in several ways on the server side. It depends on to your web project. I will show you how to do it in Asp.net MVC projects. I wrote this code in C#. Its converting the data to a pdf file. You must add ItextSharp dll files to your references to use this code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 |
using System; using System.Collections.Generic; using iTextSharp.text; using iTextSharp.text.pdf; using Mcx.Data; using System.IO; namespace ReportService.Utility { public class PdfReport { private int _totalColumn = 0; private Document _document; private Font _fontStyle; private BaseFont _baseFont; private PdfPTable _pdfTable; private PdfPCell _pdfCell; private MemoryStream _memoryStream = new MemoryStream(); public string title { get; set; } public string RaporBaslik { get; set; } public string RaporBaslikIcerik { get; set; } public List<string> sutunList; private IMcxSchema _schema; private List<IMcxFeature> _featureList; public PdfReport(IMcxSchema schema, List<IMcxFeature> featureList) { sutunList = new List<string>(); _schema = schema; _featureList = featureList; BaseFont bs = BaseFont.CreateFont(@"C:\Windows\Fonts\arialbd.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); _baseFont = bs; } public void CreateSheetHeader() { _pdfCell = new PdfPCell(new Phrase(DateTime.Now.ToString("dd/MM/yyyy"), new Font(_baseFont, 9))); _pdfCell.Colspan = _totalColumn; _pdfCell.HorizontalAlignment = Element.ALIGN_RIGHT; _pdfCell.Border = 0; _pdfCell.BackgroundColor = BaseColor.WHITE; _pdfCell.ExtraParagraphSpace = 0; _pdfTable.AddCell(_pdfCell); _pdfTable.CompleteRow(); _pdfCell = new PdfPCell(new Phrase("T.C.", new Font(_baseFont, 13))); _pdfCell.Colspan = _totalColumn; _pdfCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfCell.Border = 0; _pdfCell.BackgroundColor = BaseColor.WHITE; _pdfCell.ExtraParagraphSpace = 0; _pdfTable.AddCell(_pdfCell); _pdfTable.CompleteRow(); _pdfCell = new PdfPCell(new Phrase(title, new Font(_baseFont, 11))); _pdfCell.Colspan = _totalColumn; _pdfCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfCell.Border = 0; _pdfCell.BackgroundColor = BaseColor.WHITE; _pdfCell.ExtraParagraphSpace = 0; _pdfTable.AddCell(_pdfCell); _pdfTable.CompleteRow(); _pdfCell = new PdfPCell(new Phrase(RaporBaslikIcerik, new Font(_baseFont, 9))); _pdfCell.Colspan = _totalColumn; _pdfCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfCell.Border = 0; _pdfCell.BackgroundColor = BaseColor.WHITE; _pdfCell.ExtraParagraphSpace = 0; _pdfTable.AddCell(_pdfCell); _pdfTable.CompleteRow(); _pdfCell = new PdfPCell(new Phrase(RaporBaslik, new Font(_baseFont, 9))); _pdfCell.Colspan = _totalColumn; _pdfCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfCell.Border = 0; _pdfCell.BackgroundColor = BaseColor.WHITE; _pdfCell.ExtraParagraphSpace = 0; _pdfTable.AddCell(_pdfCell); _pdfTable.CompleteRow(); _pdfCell = new PdfPCell(new Phrase(" ", new Font(_baseFont, 9))); _pdfCell.Colspan = _totalColumn; _pdfCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfCell.Border = 0; _pdfCell.BackgroundColor = BaseColor.WHITE; _pdfCell.ExtraParagraphSpace = 0; _pdfTable.AddCell(_pdfCell); _pdfTable.CompleteRow(); _pdfCell = new PdfPCell(new Phrase(" ", new Font(_baseFont, 9))); _pdfCell.Colspan = _totalColumn; _pdfCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfCell.Border = 0; _pdfCell.BackgroundColor = BaseColor.WHITE; _pdfCell.ExtraParagraphSpace = 0; _pdfTable.AddCell(_pdfCell); _pdfTable.CompleteRow(); } public void CreateTableHeader() { _pdfCell = new PdfPCell(new Phrase("#", new Font(_baseFont, 7))); _pdfCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfCell.BackgroundColor = BaseColor.LIGHT_GRAY; _pdfTable.AddCell(_pdfCell); foreach (var item in _schema.Fields) { if (item.FieldName == null) continue; _pdfCell = new PdfPCell(new Phrase(item.FieldName, new Font(_baseFont, 7))); _pdfCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfCell.BackgroundColor = BaseColor.LIGHT_GRAY; _pdfCell.VerticalAlignment = Element.ALIGN_MIDDLE; _pdfTable.AddCell(_pdfCell); } _pdfTable.CompleteRow(); } public void CreateTableBody() { int sort = 1; foreach (var feature in _featureList) { _pdfCell = new PdfPCell(new Phrase(sort.ToString(), new Font(_baseFont, 7))); _pdfCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfCell.BackgroundColor = BaseColor.WHITE; _pdfCell.VerticalAlignment = Element.ALIGN_MIDDLE; _pdfTable.AddCell(_pdfCell); foreach (var field in feature.Schema.Fields) { _pdfCell = new PdfPCell(new Phrase(feature[field.FieldName] + "", new Font(_baseFont, 7))); _pdfCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfCell.BackgroundColor = BaseColor.WHITE; _pdfCell.VerticalAlignment = Element.ALIGN_MIDDLE; _pdfTable.AddCell(_pdfCell); } sort++; } _pdfTable.CompleteRow(); } public bool sutunAdKontrol(string sutunAd) { if (sutunList.Contains(sutunAd)) return true; else return false; } public byte[] PrepareReport() { _totalColumn = _featureList[0].FieldCount + 1; _pdfTable = new PdfPTable(_featureList[0].FieldCount + 1); _document = new Document(PageSize.A4.Rotate(), 0f, 0f, 0f, 0f); _document.SetPageSize(PageSize.A4.Rotate()); // a4 ü yan cevirmek için... _document.SetMargins(10f, 10f, 40f, 10f); _document.AddLanguage("tr-TR"); _pdfTable.WidthPercentage = 100; _pdfTable.HorizontalAlignment = Element.ALIGN_LEFT; PdfWriter.GetInstance(_document, _memoryStream); _document.Open(); float[] widthArray = new float[_totalColumn]; for (int i = 0; i < _totalColumn; i++) { if (i == 0) widthArray[i] = 10f; else widthArray[i] = 20f; } _pdfTable.SetWidths(widthArray); CreateSheetHeader(); CreateTableHeader(); CreateTableBody(); _pdfTable.HeaderRows = 8; _document.Add(_pdfTable); _document.Close(); return _memoryStream.ToArray(); } } } |
Then we will send the data with our controller method. And file must be send in the httpResponseMessage byteArrayContent. This method will be used as a service in Angular to fetch the file for downloading.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public HttpResponseMessage PdfExporting(int userId) { IMcxSchema _schema; List<IMcxFeature> _featureList; // get data from db .. PdfReport pdfObject = new PdfReport(_featureList.FirstOrDefault().Schema, _featureList); pdfObject.RaporBaslik = "Case Report"; pdfObject.RaporBaslikIcerik = ""; pdfObject.title = "AFAD"; byte[] pdfFileContent = pdfObject.PrepareReport(); //adding bytes to memory stream var dataStream = new MemoryStream(pdfFileContent); HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK); httpResponseMessage.Content = new StreamContent(dataStream); httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); httpResponseMessage.Content.Headers.ContentDisposition.FileName = "hsrtespit.pdf"; httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); return httpResponseMessage; } |
We should prepare an Angular service to get and download the pdf file. Code below should be in html file.
1 2 3 4 5 6 7 8 9 10 |
public PdfExport(userId:number):Observable<Blob> { const header = new HttpHeaders().set('content-type', 'application/octet-stream'); return this.http.get(url + 'rapor/PdfExporting' + '?userId=' + userId , {header, responseType: ResponseContentType.Blob}); } // naming excel file service public toExportFileName(excelFileName: string,extensionName: string): string { return `${excelFileName}_${new Date().getTime()}.${extensionName}`; } |
This code placed in the component code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
----- html code ------- <div class="col-md-2" *ngIf="totalRecords > 0"> <button class="btn btn-primary btn-block" id="btnPdf" (click)="pdf()"><span class="glyphicon glyphicon-download"></span> Pdf Aktar</button> </div> ----- component code ------- pdf(){ this.service.PdfExport(this.selectedUserKod) .subscribe(res => { const data = new Blob([res._body], {type: 'application/octet-stream'}); var fileName = this.service.toExportFileName("caseReport","pdf"); saveAs(data, fileName); }); } |
You must install file-saver component to save bytestream as an excel file. At the same time, you can do it with this command in node.js “npm install file-saver –save”. You should also have a look at my other post about Download Excel File In Angular2
If you have question do not forget to write from the chat button next to it or from the comment.
Recent Comments