Я написал этот код, используя несколько предыдущих примеров (в основном это блог, написанный Джеймсом МакКормаком), и я могу сохранить PDF-файл с необходимыми данными в папке в моем репо. Я ошибаюсь в том, что, пожалуй, самое простое из того, что я хочу сделать, это чтобы файл появился в нижней части браузера, чтобы конечный пользователь мог открыть его из браузера.
Вот мой код. Я добавил кнопку в свою таблицу данных, чтобы можно было создавать метки только для записей в моей отфильтрованной таблице -
{
text: 'Avery labels',
action: function (e, dt, node, config) {
$.ajax({
type: 'POST',
datatype: 'json',
url: 'Avery/AveryLabels',
data: {
'datatable': JSON.stringify(dt.rows({ filter: 'applied' }).data().toArray())
},
error: function (request) {
alert(request.responseText);
},
success: function (response) {
alert("success");
},
});
}
}
Это код моего контроллера, для того, чтобы создать ярлыки avery -
public ActionResult AveryLabels(String datatable)
{
var doc = new Document();
string path = Server.MapPath("PDF");
PdfWriter.GetInstance(doc, new FileStream(path + "/Doc1.pdf", FileMode.Create));
List<Custom_SummaryActive> custom_SummaryActive = new List<Custom_SummaryActive>();
List<int> employeeIDList = new List<int>();
custom_SummaryActive = JsonConvert.DeserializeObject<List<Custom_SummaryActive>>(datatable);
foreach (var item in custom_SummaryActive)
{
employeeIDList.Add(item.EmpID);
}
const int pageMargin = 5;
const int pageRows = 5;
const int pageCols = 2;
doc.SetMargins(pageMargin, pageMargin, pageMargin, pageMargin);
var memoryStream = new MemoryStream();
var pdfWriter = PdfWriter.GetInstance(doc, memoryStream);
doc.Open();
// Create the Label table
PdfPTable table = new PdfPTable(pageCols);
table.WidthPercentage = 100f;
table.DefaultCell.Border = 0;
var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
IList<Custom_AveryLabels> employeeData = (IList<Custom_AveryLabels>)(from emp in _PUSPERSContext.TblEmployee
where employeeIDList.Contains(emp.EmployeeID)
select new Custom_AveryLabels
{
Forename = emp.Forename,
Surname = emp.Surname,
OfficialAddressLineOne = emp.OfficialAddressLineOne,
OfficialAddressLineTwo = emp.OfficialAddressLineTwo,
OfficialAddressLineThree = emp.OfficialAddressLineThree,
OfficialAddressLineFour = emp.OfficialAddressLineFour,
OfficialAddressLineFive = emp.OfficialAddressLineFive,
OfficialPostcode = emp.OfficialPostcode
}).ToList();
foreach (var address in employeeData)
{
#region Label Construction
PdfPCell cell = new PdfPCell();
cell.Border = 0;
cell.FixedHeight = (doc.PageSize.Height - (pageMargin * 2)) / pageRows;
cell.VerticalAlignment = Element.ALIGN_MIDDLE;
var contents = new Paragraph();
contents.Alignment = Element.ALIGN_CENTER;
contents.Add(new Chunk(string.Format(address.Forename + " "), new Font(baseFont, 8f)));
contents.Add(new Chunk(string.Format(address.Surname + '\n'), new Font(baseFont, 8f)));
contents.Add(new Chunk(string.Format(address.OfficialAddressLineOne + '\n'), new Font(baseFont, 8f)));
contents.Add(new Chunk(string.Format(address.OfficialAddressLineTwo + '\n'), new Font(baseFont, 8f)));
contents.Add(new Chunk(string.Format(address.OfficialAddressLineThree + '\n'), new Font(baseFont, 8f)));
contents.Add(new Chunk(string.Format(address.OfficialAddressLineFour + '\n'), new Font(baseFont, 8f)));
contents.Add(new Chunk(string.Format(address.OfficialAddressLineFive + '\n'), new Font(baseFont, 8f)));
contents.Add(new Chunk(string.Format(address.OfficialPostcode), new Font(baseFont, 8f)));
cell.AddElement(contents);
table.AddCell(cell);
#endregion
}
doc.Add(table);
// Close PDF document and send
pdfWriter.CloseStream = false;
doc.Close();
memoryStream.Position = 0;
return File(memoryStream, "application/pdf", "DownloadName.pdf");
}
Заранее спасибо