Bläddra i källkod

Refactoring code

Feature
Safet Purkovic 4 år sedan
förälder
incheckning
2caad72122

+ 4
- 197
BlackRock.Reporting.API/Controllers/PDFGeneratorController.cs Visa fil

@@ -4,8 +4,6 @@ using BlackRock.Reporting.API.Core;
using BlackRock.Reporting.API.Core.Models;
using Microsoft.AspNetCore.Mvc;
using PuppeteerSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace BlackRock.Reporting.API.Controllers
{
@@ -29,43 +27,22 @@ namespace BlackRock.Reporting.API.Controllers
if (string.IsNullOrEmpty(url))
return BadRequest();

// url must be encoded on client side and here we do decode
var result = HttpUtility.UrlDecode(url);
// Temporary name of file which will be downloaded
var fileName = Guid.NewGuid().ToString() + ".pdf";
// Path to wwwroot folder combined with name of pdf file
string path = Path.Combine(host.ContentRootPath, $"wwwroot/pdfs/{fileName}");
// Mapping from DTO class to Puppeteer PdfOptions class. For margins and paper format
var options = mapper.Map<OptionsForPdf, PdfOptions>(pdfOptions);
await generator.Generate(result, path, options);

// Document document = new Document(PageSize.A4, 36, 36, 36 + 100, 36); // note height should be set here
// MyEvent e = new MyEvent(host);
// PdfWriter pw = PdfWriter.GetInstance(document, new FileStream(Path.Combine(host.ContentRootPath, "logtest.pdf"), FileMode.Create));
// pw.PageEvent = e;
// document.Open();

// for (int i = 0; i < 100; i++)
// {
// document.Add(new Phrase("TESTING\n"));
// }

// document.Close();

var pixels = CalculatePixels(options.MarginOptions.Top);
ModifyPDF(path, pixels);
FileStream stream = new FileStream(path, FileMode.Open);
return File(stream, "application/pdf", fileName);
}

private double CalculatePixels(string v)
{
float Result;
if(float.TryParse(v,out Result))
return 2.83*Result;
var num = float.Parse(v.Split(' ')[0]);
return 2.83*num;
}

[HttpGet("isolate/{url}")]
public async Task<IActionResult> GetIsolated([FromQuery] OptionsForPdf pdfOptions, string url = "http://localhost:3000/#/dashboard")
@@ -83,178 +60,8 @@ namespace BlackRock.Reporting.API.Controllers

await generator.Isolate(result, path, options);

var pixels = CalculatePixels(options.MarginOptions.Top);
ModifyPDF(path, pixels);


FileStream stream = new FileStream(path, FileMode.Open);
return File(stream, "application/pdf", fileName);
}

private void Nesto()
{
//string oldFile = Path.Combine(host.ContentRootPath, "0bd7e2f4-b01e-4c17-8f1e-99562d2bab4a.pdf");
string oldFile = Path.Combine(host.ContentRootPath, "oldFile.pdf");
string newFile = Path.Combine(host.ContentRootPath, "newFilxex.pdf");

// open the reader
PdfReader reader = new PdfReader(oldFile);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);

AcroFields form = reader.AcroFields;
try
{
for (int pagew = 1; pagew <= reader.NumberOfPages; pagew++)
{

}
}
catch { }

// open the writer
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();

// the pdf content
PdfContentByte cb = writer.DirectContent;

// select the font properties
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.DARK_GRAY);
cb.SetFontAndSize(bf, 8);

// write the text in the pdf content
cb.BeginText();
string text = "Some random blablablabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(1, text, 520, 640, 0);
cb.EndText();
cb.BeginText();
text = "Other random blabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(2, text, 100, 200, 0);
cb.EndText();

// create the new page and add it to the pdf
PdfImportedPage page = writer.GetImportedPage(reader, 1);
var pages = reader.GetPageN(1);
var content = writer.DirectContent;
var template = content.CreateTemplate(100, 100);
float width = 100, height = 100;
// PdfDictionary
// pages.CreateTemplate(writer,100,100);
// cb.AddTemplate(page, 0, 0);
// cb.AddTemplate()
// Document document = new Document(PageSize.A4, 36, 36, 36 + 100, 36); // note height should be set here
MyEvent e = new MyEvent(host);
//PdfWriter pw = PdfWriter.GetInstance(document, new FileStream(Path.Combine(host.ContentRootPath, "logtest.pdf"), FileMode.Create));
writer.PageEvent = e;
document.Open();

// for (int i = 0; i < 100; i++)
// {
// document.Add(new Phrase("TESTING\n"));
// }

//document.Close();
// close the streams and voilá the file should be changed :)
document.Close();
fs.Close();
writer.Close();
reader.Close();
}

private void ModifyPDF(string path,double marginTop)
{
var filePath = path;
byte[] bytes = System.IO.File.ReadAllBytes(filePath);
var pdfReader = new PdfReader(bytes);
using (Stream output = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (PdfStamper pdfStamper = new PdfStamper(pdfReader, output))
{
for (int pageIndex = 1; pageIndex <= pdfReader.NumberOfPages; pageIndex++)
{
pdfStamper.FormFlattening = false;
Rectangle pageRectangle = pdfReader.GetPageSizeWithRotation(pageIndex);
PdfContentByte pdfData = pdfStamper.GetOverContent(pageIndex);
pdfData.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 10);
PdfGState graphicsState = new PdfGState
{
FillOpacity = 0.3F
};
pdfData.SetGState(graphicsState);
Image image = Image.GetInstance(Path.Combine(host.ContentRootPath, "logo.png"));
var OriginalWidth = image.Width;
var OriginialHeight = image.Height;
var scale = OriginalWidth/OriginialHeight;
OriginialHeight = (float)marginTop-5;
OriginalWidth = OriginialHeight*scale;
image.ScaleAbsoluteWidth(OriginalWidth);
image.ScaleAbsoluteHeight(OriginialHeight);
image.SetAbsolutePosition(5,pageRectangle.Height-OriginialHeight-5);
pdfData.AddImage(image);
// pdfData.BeginText();

// // select the font properties
// BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
// pdfData.SetColorFill(BaseColor.BLACK);
// pdfData.SetFontAndSize(bf, 8);

// write the text in the pdf content
// pdfData.BeginText();
// string text = "Faisal Pathan";
// // put the alignment and coordinates here
// pdfData.ShowTextAligned(1, text, 70, 775, 0);
// pdfData.EndText();

// pdfData.BeginText();
// string text1 = "faisalmpathan@gmail.com";
// pdfData.ShowTextAligned(1, text1, 550, 775, 0);
// pdfData.ShowTextAligned(0,"logo",pageRectangle.Width/2,pageRectangle.Height-15,0);
// pdfData.EndText();

}
}
output.Close();
output.Dispose();
}
}
}
public partial class MyEvent : PdfPageEventHelper
{
public MyEvent(IHostEnvironment host)
{
this.host = host;
}
iTextSharp.text.Image image1;
PdfPTable header = new PdfPTable(3);
private readonly IHostEnvironment host;

public override void OnOpenDocument(PdfWriter writer, Document document)
{
image1 = Image.GetInstance(Path.Combine(host.ContentRootPath, "logo.png"));

image1.SetAbsolutePosition(20, (document.PageSize.Height - 120));

//header.WriteSelectedRows(0, -1, document.Left, document.Top, writer.DirectContent);

}

public override void OnEndPage(PdfWriter writer, Document document)
{


PdfPTable tbHeader = new PdfPTable(1);

tbHeader.AddCell(image1);
//tbHeader.TotalWidth = image1.Width;
// tbHeader.WriteSelectedRows(0, -1, 10, document.PageSize.Height - 15, writer.DirectContent);
tbHeader.WriteSelectedRows(0, -1, document.PageSize.Width / 2 - image1.Width / 2, document.PageSize.Height - 15, writer.DirectContent);
}
}
}

+ 48
- 122
BlackRock.Reporting.API/Persistence/PdfGenerator.cs Visa fil

@@ -1,15 +1,11 @@
using System.Data.Common;
using BlackRock.Reporting.API.Core;
using BlackRock.Reporting.API.Core.Models;
using iTextSharp.text;
using iTextSharp.text.pdf;
using PuppeteerSharp;
using iTextSharp;
using iTextSharp.text.xml;

namespace BlackRock.Reporting.API.Persistence
{
public class PdfGenerator : IPdfGenerator
{
private readonly IHostEnvironment host;
@@ -29,25 +25,17 @@ namespace BlackRock.Reporting.API.Persistence
{
await page.GoToAsync(url, WaitUntilNavigation.DOMContentLoaded);

// await modifyPage(page,param);
var allResultsSelector = ".chartjs-render-monitor";
await page.WaitForSelectorAsync(allResultsSelector);
await EvaluateScript(page, "dist/main.js");
await page.PdfAsync(path, options
// new PdfOptions{
// Landscape = true,
// PrintBackground = true,
// Format = PuppeteerSharp.Media.PaperFormat.Letter
// }
);

}
// POST header image
await page.PdfAsync(path, options);

// ModifyPdf(path);
var pixels = CalculatePixels(options.MarginOptions.Top);
ModifyPDF(path, pixels);
}
}

public async Task Isolate(string url, string path, PdfOptions options)
{
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
@@ -59,131 +47,69 @@ namespace BlackRock.Reporting.API.Persistence
using (var page = await browser.NewPageAsync())
{
await page.GoToAsync(url, WaitUntilNavigation.DOMContentLoaded);

var allResultsSelector = ".chartjs-render-monitor";
await page.WaitForSelectorAsync(allResultsSelector);
await page.EvaluateFunctionAsync("() => document.getElementById('sel').selectedIndex = "+((options.Landscape)?1:0));
await page.EvaluateFunctionAsync("() => document.getElementById('sel').selectedIndex = " + ((options.Landscape) ? 1 : 0));
await page.ClickAsync("button.dugme");
await EvaluateScript(page, "dist/main.js");
await EvaluateScript(page, "dist/main2.js");
await page.PdfAsync(path, options
// new PdfOptions{
// PrintBackground = true,
// Format = PuppeteerSharp.Media.PaperFormat.Letter
// }
);
await page.PdfAsync(path, options);

}
}

private async Task EvaluateScript(Page page, string fileName)
{
string path2 = Path.Combine(host.ContentRootPath, fileName);
var result = await System.IO.File.ReadAllTextAsync(path2);
await page.EvaluateExpressionAsync(result);
}
private void AddAnImage()
private void ModifyPDF(string path, double marginTop)
{
using (var inputPdfStream = new FileStream(Path.Combine(host.ContentRootPath, "newFile.pdf"), FileMode.Open))
using (var inputImageStream = new FileStream(Path.Combine(host.ContentRootPath, "pic.jpg"), FileMode.Open))
using (var outputPdfStream = new FileStream(Path.Combine(host.ContentRootPath, "newFilesesses.pdf"), FileMode.Create))
var filePath = path;
byte[] bytes = System.IO.File.ReadAllBytes(filePath);
var pdfReader = new PdfReader(bytes);
using (Stream output = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
PdfReader reader = new PdfReader(inputPdfStream);
PdfStamper stamper = new PdfStamper(reader, outputPdfStream);
PdfContentByte pdfContentByte = stamper.GetOverContent(1);
var image = iTextSharp.text.Image.GetInstance(inputImageStream);
image.ScaleAbsolute(40, 40);
image.SetAbsolutePosition(0, 0);
pdfContentByte.AddImage(image);
stamper.Close();
}
}
private void ModifyPdf(string oldFile)
{
string formFile = Path.Combine(host.ContentRootPath, "newFile.pdf");
string newFile = Path.Combine(host.ContentRootPath, "newFiles.pdf");
// string newFile = Path.Combine(host.ContentRootPath,"newFile.pdf");
PdfReader reader = new PdfReader(formFile);
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create)))
{
AcroFields fields = stamper.AcroFields;

// set form fields
fields.SetField("name", "John Doe");
fields.SetField("address", "xxxxx, yyyy");
fields.SetField("postal_code", "12345");
fields.SetField("email", "johndoe@xxx.com");

// flatten form fields and close document
stamper.FormFlattening = true;
stamper.Close();
}
}

private void Nesto()
{
//string oldFile = Path.Combine(host.ContentRootPath, "0bd7e2f4-b01e-4c17-8f1e-99562d2bab4a.pdf");
string oldFile = "oldFile.pdf";
string newFile = Path.Combine(host.ContentRootPath, "newFile.pdf");

// open the reader
PdfReader reader = new PdfReader(oldFile);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);

AcroFields form = reader.AcroFields;
try
{
for (int pagew = 1; pagew <= reader.NumberOfPages; pagew++)
using (PdfStamper pdfStamper = new PdfStamper(pdfReader, output))
{

for (int pageIndex = 1; pageIndex <= pdfReader.NumberOfPages; pageIndex++)
{
pdfStamper.FormFlattening = false;
Rectangle pageRectangle = pdfReader.GetPageSizeWithRotation(pageIndex);
PdfContentByte pdfData = pdfStamper.GetOverContent(pageIndex);
pdfData.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 10);
PdfGState graphicsState = new PdfGState
{
FillOpacity = 0.3F
};
pdfData.SetGState(graphicsState);
Image image = Image.GetInstance(Path.Combine(host.ContentRootPath, "logo.png"));
var OriginalWidth = image.Width;
var OriginialHeight = image.Height;
var scale = OriginalWidth / OriginialHeight;
OriginialHeight = (float)marginTop - 5;
OriginalWidth = OriginialHeight * scale;
image.ScaleAbsoluteWidth(OriginalWidth);
image.ScaleAbsoluteHeight(OriginialHeight);
image.SetAbsolutePosition(5, pageRectangle.Height - OriginialHeight - 5);
pdfData.AddImage(image);
}
}
output.Close();
output.Dispose();
}
catch { }

// open the writer
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();

// the pdf content
PdfContentByte cb = writer.DirectContent;

// select the font properties
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.DARK_GRAY);
cb.SetFontAndSize(bf, 8);

// write the text in the pdf content
cb.BeginText();
string text = "Some random blablablabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(1, text, 520, 640, 0);
cb.EndText();
cb.BeginText();
text = "Other random blabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(2, text, 100, 200, 0);
cb.EndText();

// create the new page and add it to the pdf
PdfImportedPage page = writer.GetImportedPage(reader, 1);
var pages = reader.GetPageN(1);
var content = writer.DirectContent;
var template = content.CreateTemplate(100, 100);
float width = 100, height = 100;
// PdfDictionary
// pages.CreateTemplate(writer,100,100);
// cb.AddTemplate(page, 0, 0);
// cb.AddTemplate()
}

// close the streams and voilá the file should be changed :)
document.Close();
fs.Close();
writer.Close();
reader.Close();
private double CalculatePixels(string v)
{
float Result;
if (float.TryParse(v, out Result))
return 2.83 * Result;
var num = float.Parse(v.Split(' ')[0]);
return 2.83 * num;
}
}
}

+ 1
- 1
BlackRock.Reporting.API/dist/main.js
Filskillnaden har hållits tillbaka eftersom den är för stor
Visa fil


Laddar…
Avbryt
Spara