Files
pdf-xrechnung/lib/append.go
T

98 lines
2.1 KiB
Go
Executable File

package lib
import (
"bytes"
"errors"
"fmt"
"os"
"path"
"path/filepath"
"strings"
"github.com/pdfcpu/pdfcpu/pkg/api"
"github.com/pdfcpu/pdfcpu/pkg/pdfcpu/model"
)
func AppendToPdf(inputPdfFilePath string, inputXmlFilePath string, outputFilePath string) error {
logger := GetDebugLogger()
logger.Log(fmt.Sprintf("enter appendToPdf(%s, %s, %s)", inputPdfFilePath, inputXmlFilePath, outputFilePath))
defer func() {
logger.Log("leave appendToPdf")
}()
if inputPdfFilePath == "" {
return errors.New("no input pdf file specified")
}
if inputXmlFilePath == "" {
inputXmlFilePath = strings.TrimSuffix(inputPdfFilePath, filepath.Ext(inputPdfFilePath)) + ".xml"
}
if outputFilePath == "" {
outputFilePath = strings.TrimSuffix(
inputPdfFilePath,
filepath.Ext(inputPdfFilePath),
) + "_xml.pdf"
}
logger.Log(
fmt.Sprintf(
"pdfInput: '%s' xmlInput: '%s' output: '%s'",
inputPdfFilePath,
inputXmlFilePath,
outputFilePath,
),
)
inputFile, err := os.Open(inputPdfFilePath)
if err != nil {
return err
}
defer inputFile.Close()
dest := bytes.Buffer{}
err = api.AddAttachments(
inputFile,
&dest,
[]string{inputXmlFilePath},
true,
model.NewDefaultConfiguration(),
)
if err != nil {
return err
}
source := bytes.NewReader(dest.Bytes())
dest = bytes.Buffer{}
err = api.AddProperties(source, &dest, map[string]string{
"DocumentFileName": path.Base(inputXmlFilePath),
"DocumentType": "INVOICE",
"ConformanceLevel": "EN 16931",
"SchemasSchema": "Factur-X PDFA Extension Schema",
"SchemasPrefix": "fx",
"SchemasPropertyName": "DocumentFileName",
"SchemasPropertyValueType": "Text",
"SchemasPropertyCategory": "external",
"SchemasPropertyDescription": "The name of the embedded XML document",
}, model.NewDefaultConfiguration())
if err != nil {
return err
}
var outputFile *os.File
outputFile, err = os.Create(outputFilePath)
if err != nil {
return err
}
defer outputFile.Close()
_, err = outputFile.Write(dest.Bytes())
if err != nil {
return err
}
return nil
}