Home > database >  Open Pdf From API On Winforms Project in .NET
Open Pdf From API On Winforms Project in .NET

Time:10-08

I have an API that opens a pdf file in a browser, I want to call that programmatically from another WinForms project(Both in the same solution).

Here is the Controller and setups:

app.UseCors();

[EnableCors("*")]
[Route("api/pdfcreator")]
[ApiController]
public class PdfCreatorController : Controller
{
    private IConverter _converter;
    public PdfCreatorController(IConverter converter)
    {
        _converter = converter;
    }
    [HttpGet]
    public IActionResult CreatePDF()
    {
        var globalSettings = new GlobalSettings
        {
            ColorMode = ColorMode.Color,
            Orientation = Orientation.Portrait,
            PaperSize = PaperKind.A4,
            Margins = new MarginSettings { Top = 10 },
            DocumentTitle = "PDF Report",
            //Out = @"D:\PDFCreator\Employee_Report.pdf"
        };
        var objectSettings = new ObjectSettings
        {
            PagesCount = true,
            HtmlContent = TemplateGenerator.GetHTMLString(),
            WebSettings = { DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(Directory.GetCurrentDirectory(), "assets", "styles.css") },
            HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Page [page] of [toPage]", Line = true },
            FooterSettings = { FontName = "Arial", FontSize = 9, Line = true, Center = "Report Footer" }
        };
        var pdf = new HtmlToPdfDocument()
        {
            GlobalSettings = globalSettings,
            Objects = { objectSettings }
        };
        //_converter.Convert(pdf);
        var file = _converter.Convert(pdf);
        //return Ok("Successfully created PDF document.");
        return File(file, "application/pdf");
    }
}

Here is how I want to call it:

getApi("http://localhost:44344/api/pdfcreator");



public string GetApi(string ApiUrl)
    {
        var responseString = "";
        var request = (HttpWebRequest)WebRequest.Create(ApiUrl);
        request.Method = "GET";
        request.ContentType = "application/pdf";

        using (var response1 = request.GetResponse())
        {
            using (var reader = new StreamReader(response1.GetResponseStream()))
            {
                responseString = reader.ReadToEnd();
            }
        }
        return responseString;

    }

But the response here is a string, while we are interested in calling the API only!

How to do this?

Considering this, It is not clear how to send the response to the browser again after parsing it!

CodePudding user response:

So from your comment in the question I assume you want to show the file in the browser from the winforms application.

Then you can do this. It will launch the default browser and go to the file.

System.Diagnostics.Process.Start("http://localhost:44344/api/pdfcreator");
  • Related