Web API Swagger 文档导出为 PDF

Web API Swagger documentation export to PDF(Web API Swagger 文档导出为 PDF)
本文介绍了Web API Swagger 文档导出为 PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据文档(

这是我下面需要在 startup.cs 文件中配置的代码.

 public void Configure(IApplicationBuilder app, IHostingEnvironment env){app.UseStaticFiles();app.UseSwagger();app.UseSwaggerUI(c =>{c.SwaggerEndpoint(Configuration["Swagger:swaggerurl"], Configuration["Swagger:swaggertitle"]);c.InjectJavascript("/swagger-ui/custom.js");c.InjectJavascript("/swagger-ui/rapipdf-min.js");});if (env.IsDevelopment()){_logger.LogInformation("配置开发环境");app.UseDeveloperExceptionPage();}别的{_logger.LogInformation("生产环境配置");应用程序.UseHsts();}app.UseAuthentication();app.UseMiddleware<ErrorHandlerMiddleware>();//删除了处理令牌的中间件,现在使用策略和身份验证方案进行了更改//app.UseMiddleware<TokenManagerMiddleware>();app.UseHttpsRedirection();app.UseMvc();}

在上面的代码中,我们需要了解的是,我们要注入两个js文件,一个是自定义js,另一个是插件,所以它会添加到Swagger UI索引页面的head部分.

这是我在 Custom.js 中的以下代码

window.addEventListener("load", function () {自定义SwaggerUI();});函数customizeSwaggerUI() {设置超时(函数(){var tag = '<rapi-pdf style="display:none" id="thedoc"></rapi-pdf>';var btn = '<button id="btn" style="font-size:16px;padding: 6px 16px;text-align: center;white-space: nowrap;background-color: orangered;color: white;border:0px 实心#333;光标:指针;"type="button" onclick="downloadPDF()">下载API文档</button>';var oldhtml = document.getElementsByClassName('info')[0].innerHTML;document.getElementsByClassName('info')[0].innerHTML = oldhtml + '</br>'+ 标签 + '</br>'+ btn;}, 1200);}函数下载PDF() {var client = new XMLHttpRequest();client.overrideMimeType("application/json");client.open('GET', 'v1/swagger.json');var jsonAPI = "";client.onreadystatechange = function () {if (client.responseText != 'undefined' && client.responseText != "") {jsonAPI = client.responseText;如果(jsonAPI!="){让 docEl = document.getElementById("thedoc");var key = jsonAPI.replace('"授权:承载{token}"', "");让 objSpec = JSON.parse(key);docEl.generatePdf(objSpec);}}}客户端.send();}

就是这样.现在您可以下载 PDF 格式的 API 文档了.

希望这将有助于某人集成相同类型的功能.

In according to the documentation (http://swagger.io/open-source-integrations/) there are plugins for Java to Export Swagger documentation to PDF, I just have a look the documentation but I can't see anything regarding .NET.

My question is: is there something similar to the Java Plugin swagger2markup, swagger2markup-gradle-plugin in .NET or another way to export the PDF Documentation from WEB API?

thanks

解决方案

I have implemented the same thing in my ongoing project. We can download PDF document of all the API's. I have done using Rapi-Pdf plugin through which we can generate PDF of swagger Json. Its in Dotnet core 2.1.

Here is my below code which we need to configure in startup.cs file.

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseStaticFiles();
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint(Configuration["Swagger:swaggerurl"], Configuration["Swagger:swaggertitle"]);
            c.InjectJavascript("/swagger-ui/custom.js");
            c.InjectJavascript("/swagger-ui/rapipdf-min.js");
        });

        if (env.IsDevelopment())
        {
            _logger.LogInformation("Configuring for Development environment");
            app.UseDeveloperExceptionPage();
        }
        else
        {
            _logger.LogInformation("Configuring for Production environment");
            app.UseHsts();
        }
        app.UseAuthentication();
        app.UseMiddleware<ErrorHandlerMiddleware>();
        //removed middleware to handle token, now changed with policies and auth schemes
        //app.UseMiddleware<TokenManagerMiddleware>();
        app.UseHttpsRedirection();
        app.UseMvc();
    }

In the above code what we need to understand is, we have to inject two js files one is custom js and another is plugin so it will added in head section of Swagger UI index page.

this is my below code which is inside Custom.js

window.addEventListener("load", function () {
        customizeSwaggerUI();
    });
function customizeSwaggerUI() {
    setTimeout(function () {        
        var tag = '<rapi-pdf style="display:none" id="thedoc"> </rapi-pdf>';
        var btn = '<button id="btn" style="font-size:16px;padding: 6px 16px;text-align: center;white-space: nowrap;background-color: orangered;color: white;border: 0px solid #333;cursor: pointer;" type="button" onclick="downloadPDF()">Download API Document </button>';
        var oldhtml = document.getElementsByClassName('info')[0].innerHTML;
        document.getElementsByClassName('info')[0].innerHTML = oldhtml + '</br>' + tag + '</br>' + btn;
    }, 1200);
}
function downloadPDF() {
    var client = new XMLHttpRequest();
    client.overrideMimeType("application/json");
    client.open('GET', 'v1/swagger.json');
    var jsonAPI = "";
    client.onreadystatechange = function () {
        if (client.responseText != 'undefined' && client.responseText != "") {
            jsonAPI = client.responseText;
            if (jsonAPI != "") {
                let docEl = document.getElementById("thedoc");
                var key = jsonAPI.replace('"Authorization: Bearer {token}"', "");
                let objSpec = JSON.parse(key);
                docEl.generatePdf(objSpec);
            }
        }
    }
    client.send();   
}

That's it. Now you can download your API document in PDF format.

Hope this will help someone to integrate the same kind of functionality.

这篇关于Web API Swagger 文档导出为 PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
quot;Overflowquot; compiler error with -9223372036854775808L(编译器错误-9223372036854775808L(Q;溢出Q))
Visual Studio 2010 ReportViewer Assembly References(Visual Studio 2010 ReportViewer程序集引用)
Weird behaviour when I open a reportviewer in WPF(在WPF中打开报表查看器时出现奇怪的行为)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)