Konvertieren eines DOCX in einen DOTM mit einer API der dritten Party in SharePoint über Power Automate?C#

Ein Treffpunkt für C#-Programmierer
Anonymous
 Konvertieren eines DOCX in einen DOTM mit einer API der dritten Party in SharePoint über Power Automate?

Post by Anonymous »

Ich möchte eine beliebige DOCX -Datei in einen DOTM konvertieren. Im Setup sollten alle DOCX -Dateien die Möglichkeit haben, eine DOTM -Datei in einem separaten Dateipfad zu erstellen. Kann es einsetzen, von Docx in DOTM zu konvertieren - ich habe einige Websites gefunden und könnte sie wahrscheinlich als benutzerdefinierten Anschluss einbeziehen, aber ich habe mich gefragt, ob Sie irgendwelche Lösungen daneben haben? Ich bin nicht viel, um den 3. Platz zu durchlaufen. Party -APIs, da einige von ihnen zwielichtig erscheinen und andere einen schweren Paygate haben. Haben Sie Erfahrung in Bezug auf dieses Problem/Vorschläge für APIs, die ich nutzen könnte?

Code: Select all

using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Azure.Functions.Worker;
using System.Net;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Net.Http.Headers;
using Azure.Storage.Blobs;

namespace FunctionAppDoc_x2tm
{

public class DocxToDotmFunction
{
private readonly ILogger _logger;

public DocxToDotmFunction(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger();
}

[Function("ConvertDocxToDotm")]
public async Task Run(
[HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req)
{

req.Headers.TryGetValues("Content-Type", out var contentTypeValues);
var contentType = contentTypeValues?.FirstOrDefault();

if (string.IsNullOrEmpty(contentType) || !contentType.Contains("multipart/form-data"))
{
var badResponse = req.CreateResponse(HttpStatusCode.BadRequest);
await badResponse.WriteStringAsync("Invalid or missing Content-Type header.");
return badResponse;
}

var boundary = GetBoundary(contentType);
if (string.IsNullOrEmpty(boundary))
{
var badResponse = req.CreateResponse(HttpStatusCode.BadRequest);
await badResponse.WriteStringAsync("Could not determine multipart boundary.");
return badResponse;
}

var reader = new MultipartReader(boundary, req.Body);
MultipartSection section;
Stream? fileStream = null;
string? fileName = null;

while ((section = await reader.ReadNextSectionAsync()) != null)
{
var hasContentDispositionHeader =
ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);

if (hasContentDispositionHeader &&  contentDisposition?.DispositionType == "form-data")
{
if (contentDisposition.Name.Value == "file")
{
fileName = contentDisposition.FileName.Value ?? "uploaded.docx";
fileStream = new MemoryStream();
await section.Body.CopyToAsync(fileStream);
fileStream.Position = 0;
}
}
}

if (fileStream == null)
{
var badResponse = req.CreateResponse(HttpStatusCode.BadRequest);
await badResponse.WriteStringAsync("No file found in request.");
return badResponse;
}

try
{
using (var dotmStream = new MemoryStream())
{
var stopwatch = System.Diagnostics.Stopwatch.StartNew();

var uploadStopwatch = System.Diagnostics.Stopwatch.StartNew();
string connectionString = Environment.GetEnvironmentVariable("AzureWebJobsStorage");
string containerName = "converted-files";
string fileName2 = "converted.dotm";

var blobServiceClient = new BlobServiceClient(connectionString);
var containerClient = blobServiceClient.GetBlobContainerClient(containerName);
await containerClient.CreateIfNotExistsAsync();

var blobClient = containerClient.GetBlobClient(fileName2);

// Upload stream
dotmStream.Position = 0;
await blobClient.UploadAsync(dotmStream, overwrite: true);

await fileStream.CopyToAsync(dotmStream);
dotmStream.Position = 0;

_logger.LogInformation($"Filename: {fileName}, Length: {fileStream?.Length}");

using (var wordDoc = WordprocessingDocument.Open(dotmStream, true))
{
wordDoc.ChangeDocumentType(WordprocessingDocumentType.MacroEnabledTemplate);
// No SaveAs needed — we're working in memory
}

dotmStream.Position = 0;
var response = req.CreateResponse(HttpStatusCode.OK);
response.Headers.Add("Content-Type", "application/vnd.ms-word.template.macroEnabled.12");
response.Headers.Add("Content-Disposition", $"attachment; filename=\"converted.dotm\"");
await response.Body.WriteAsync(dotmStream.ToArray());

stopwatch.Stop();
_logger.LogInformation($"Function execution time: {stopwatch.ElapsedMilliseconds} ms");
uploadStopwatch.Stop();
_logger.LogInformation($"Blob upload time: {uploadStopwatch.ElapsedMilliseconds} ms");

return response;
}

}
catch (Exception ex)
{
_logger.LogError($"Unhandled exception: {ex.Message}\n{ex.StackTrace}");

var errorResponse = req.CreateResponse(HttpStatusCode.InternalServerError);
await errorResponse.WriteStringAsync("An error occurred: " + ex.Message);
return errorResponse;
}

}

private string? GetBoundary(string? contentType)
{
if (string.IsNullOrEmpty(contentType))
return null;

var elements = contentType.Split(';');
var boundaryElement = elements.FirstOrDefault(t =>
t.Trim().StartsWith("boundary=", StringComparison.OrdinalIgnoreCase));

return boundaryElement?.Split('=')[1].Trim('"');
}
}
}

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post