예제 #1
0
 public OpenXMLtoFlowDocument(string openxmlfilename)
 {
     if (Document.Editor.My.Computer.FileSystem.FileExists(openxmlfilename))
     {
         DocumentFormat.OpenXml.Validation.OpenXmlValidator validator = new DocumentFormat.OpenXml.Validation.OpenXmlValidator();
         int count = 0;
         //For Each [error] As Validation.ValidationErrorInfo In validator.Validate(WordprocessingDocument.Open(openxmlfilename, True))
         //    count += 1
         //    MessageBox.Show([error].Description)
         //Next
         if (count == 0)
         {
             OpenXMLFile = WordprocessingDocument.Open(openxmlfilename, true);
         }
         else
         {
             MessageBoxDialog m = new MessageBoxDialog("OpenXML File is invalid!", "Error", null, null);
             m.MessageImage.Source = new BitmapImage(new Uri("pack://application:,,,/Images/Common/error32.png"));
             m.Owner = Document.Editor.My.Windows.MainWindow;
             m.ShowDialog();
         }
     }
     else
     {
         MessageBoxDialog m = new MessageBoxDialog("File Not Found!", "Error", null, null);
         m.MessageImage.Source = new BitmapImage(new Uri("pack://application:,,,/Images/Common/error32.png"));
         m.Owner = Document.Editor.My.Windows.MainWindow;
         m.ShowDialog();
         throw new Exception();
     }
 }
예제 #2
0
        /// <summary>
        /// Validates an excel style sheet
        /// </summary>
        /// <param name="styleSheet">The style sheet to validate</param>
        private static void ValidateStylesheet(Stylesheet styleSheet)
        {
            var validator        = new DocumentFormat.OpenXml.Validation.OpenXmlValidator();
            var validationErrors = validator.Validate(styleSheet).ToList();

            if (validationErrors.Count > 0)
            {
                Console.WriteLine($"There were validation errors with the style sheet {string.Join(Environment.NewLine, validationErrors.Select(r => r.Description))}");
            }
        }
예제 #3
0
        public byte[] GetDocument()
        {
            FooterPart footerPart   = this.document.MainDocumentPart.GetPartsOfType <FooterPart>().First();
            string     footerPartId = this.document.MainDocumentPart.GetIdOfPart(footerPart);

            var sectionProperties = new SectionProperties(      // 1440 = 1 inch, 1728 = 1.2 inch
                new FooterReference()
            {
                Type = HeaderFooterValues.Default, Id = footerPartId
            },
                new FooterReference()
            {
                Type = HeaderFooterValues.Even, Id = footerPartId
            },
                new FooterReference()
            {
                Type = HeaderFooterValues.First, Id = footerPartId
            },
                new PageSize()
            {
                Width = 12240, Height = 15840
            },
                new PageMargin()
            {
                Left = 1080, Right = 1080, Top = 1440, Bottom = 1728, Gutter = 0, Header = 720, Footer = 720
            },
                new Columns()
            {
                Space = "720"
            },
                new DocGrid()
            {
                LinePitch = 360
            });

            this.document.MainDocumentPart.Document.Body.Append(sectionProperties);

            // Bug in DocumentFormat.OpenXml adding <numberingIdMacAtClean> at an incorrect location in the document
            var numberingPart           = this.document.MainDocumentPart.NumberingDefinitionsPart;
            var numberingIdMacAtCleanup = numberingPart.Numbering.OfType <NumberingIdMacAtCleanup>().FirstOrDefault();

            if (numberingIdMacAtCleanup != null)
            {
                numberingIdMacAtCleanup.Remove();
            }

            DocumentFormat.OpenXml.Validation.OpenXmlValidator           validator = new DocumentFormat.OpenXml.Validation.OpenXmlValidator(FileFormatVersions.Office2010);
            List <DocumentFormat.OpenXml.Validation.ValidationErrorInfo> errors    = validator.Validate(this.document).ToList();

            if (errors.Count > 0)
            {
                Log.For(this).Error("Exporting IG with id " + this.implementationGuide.Id + " produced the following OpenXml validation errors: ");

                foreach (var error in errors)
                {
                    Log.For(this).Error("Description: " + error.Description + "\r\nPath: " + error.Path + "\r\n");
                }
            }

            this.document.Close();

            // Get the data back from the reader now that the doc is saved/closed
            this.docStream.Position = 0;
            byte[] buffer = new byte[this.docStream.Length];
            this.docStream.Read(buffer, 0, (int)this.docStream.Length);

            return(buffer);
        }
예제 #4
0
        static void InsertImageTest(Sheet sheet, WorksheetPart sheetPart)
        {
            var filepath = System.IO.Path.GetFullPath(@"..\..\test.jpg");
            int widthPx = 100, heightPx = 100;
            int rowIndex = 2, colomnIndex = 3;
            int rowOffsetPx = 5, columnOffsetPx = 10;

            var imageType = ImagePartType.Jpeg;
            var noChangeAspect = true;
            var noCrop = false;
            var noMove = false;
            var noResize = false;
            var noRotation = false;
            var noSelection = false;

            float imageResX, imageResY;
            using (var bmp = Image.FromFile(filepath) as Bitmap)
            {
                imageResX = bmp.HorizontalResolution;
                imageResY = bmp.VerticalResolution;
            }
            var widthEmu = CalcEmuScale(widthPx, imageResX);
            var heightEmu = CalcEmuScale(heightPx, imageResY);
            var columnOffsetEmu = CalcEmuScale(columnOffsetPx, imageResY);
            var rowOffsetEmu = CalcEmuScale(rowOffsetPx, imageResX);

            var drawingsPart = sheetPart.DrawingsPart ?? sheetPart.AddNewPart<DrawingsPart>();

            if (!sheetPart.Worksheet.ChildElements.OfType<Drawing>().Any())
            {
                sheetPart.Worksheet.Append(new Drawing() { Id = sheetPart.GetIdOfPart(drawingsPart) });
            }

            if (drawingsPart.WorksheetDrawing == null)
            {
                drawingsPart.WorksheetDrawing = new Xdr.WorksheetDrawing();
            }
            var sheetDrawing = drawingsPart.WorksheetDrawing;

            var imagePart = drawingsPart.AddImagePart(imageType);

            using (var stream = new FileStream(filepath, FileMode.Open))
            {
                imagePart.FeedData(stream);
            }

            var nvps = sheetDrawing.Descendants<Xdr.NonVisualDrawingProperties>();
            var nvpId = (nvps.Count() > 0) ? (UInt32Value)nvps.Max(prop => prop.Id.Value) + 1 : 1U;

            var pictureLocks = new A.PictureLocks()
            {
                NoChangeAspect = noChangeAspect,
                NoCrop = noCrop,
                NoMove = noMove,
                NoResize = noResize,
                NoRotation = noRotation,
                NoSelection = noSelection,
            };

            var oneCellAnchor = new Xdr.OneCellAnchor(
                new Xdr.FromMarker()
                {
                    ColumnId = new Xdr.ColumnId((colomnIndex - 1).ToString()),
                    RowId = new Xdr.RowId((rowIndex - 1).ToString()),
                    ColumnOffset = new Xdr.ColumnOffset(columnOffsetEmu.ToString()),
                    RowOffset = new Xdr.RowOffset(rowOffsetEmu.ToString()),
                },

                new Xdr.Extent() { Cx = widthEmu, Cy = heightEmu, },

                new Xdr.Picture(
                    new Xdr.NonVisualPictureProperties(
                        new Xdr.NonVisualDrawingProperties() { Id = nvpId, Name = Path.GetFileName(filepath), Description = filepath, },
                        new Xdr.NonVisualPictureDrawingProperties(pictureLocks)
                        ),
                    new Xdr.BlipFill(
                        new A.Blip() { Embed = drawingsPart.GetIdOfPart(imagePart), CompressionState = A.BlipCompressionValues.Print },
                        new A.Stretch(new A.FillRectangle())
                        ),
                    new Xdr.ShapeProperties(
                        new A.Transform2D(
                            new A.Offset() { X = 0, Y = 0, },
                            new A.Extents() { Cx = widthEmu, Cy = heightEmu }
                            ),
                        new A.PresetGeometry() { Preset = A.ShapeTypeValues.Rectangle }
                        )
                    ),
                new Xdr.ClientData());

            sheetDrawing.Append(oneCellAnchor);

            var errors = new DocumentFormat.OpenXml.Validation.OpenXmlValidator().Validate(sheetPart);
            foreach (var err in errors)
            {
                Console.WriteLine(err.Description);
            }
            if(errors.Count() > 0)
            {
                Console.Read();
            }
        }
예제 #5
0
        private static void GeneratePicture(WorksheetPart worksheetPart, IXLPicture picture)
        {
            if (!File.Exists(picture.FilePath))
            {
                throw new ArgumentException("image file not found: " + picture.FilePath);
            }

            var drawingsPart = worksheetPart.DrawingsPart ?? worksheetPart.AddNewPart<DrawingsPart>();

            var worksheet = worksheetPart.Worksheet;
            if (!worksheet.ChildElements.OfType<Drawing>().Any())
            {
                var drawing = new Drawing()
                {
                    Id = worksheetPart.GetIdOfPart(drawingsPart),
                };
                worksheet.InsertBefore(drawing, worksheet.Last());
            }

            if (drawingsPart.WorksheetDrawing == null)
            {
                drawingsPart.WorksheetDrawing = new Xdr.WorksheetDrawing();
            }
            var sheetDrawing = drawingsPart.WorksheetDrawing;

            var imagePart = drawingsPart.AddImagePart(XlPictureTypeConverter.Convert(picture.Type));
            int imageWidth, imageHeight;
            float imageResX, imageResY;
            using (var stream = new FileStream(picture.FilePath, FileMode.Open))
            {
                using (var bitmap = new System.Drawing.Bitmap(stream))
                {
                    imageWidth = bitmap.Width;
                    imageHeight = bitmap.Height;
                    imageResX = bitmap.HorizontalResolution;
                    imageResY = bitmap.VerticalResolution;
                }

                stream.Seek(0, SeekOrigin.Begin);
                imagePart.FeedData(stream);
            }

            if (picture.WidthPx == default(int))
            {
                picture.WidthPx = imageWidth;
            }
            if (picture.HeightPx == default(int))
            {
                picture.HeightPx = imageHeight;
            }

            var nvps = sheetDrawing.Descendants<Xdr.NonVisualDrawingProperties>();
            var nvpId = (nvps.Count() > 0) ? (UInt32Value)nvps.Max(prop => prop.Id.Value) + 1 : 1U;

            var pictureLocks = new A.PictureLocks()
            {
                NoChangeAspect = !picture.CanUserChangeAspect,
                NoCrop = !picture.CanUserCrop,
                NoMove = !picture.CanUserMove,
                NoResize = !picture.CanUserResize,
                NoRotation = !picture.CanUserRotate,
                NoSelection = !picture.CanUserSelect,
            };

            OpenXmlCompositeElement cellAnchor;
            {
                var markers = picture.GetMarkers();
                var markerCount = markers.Count();
                if (markerCount == 0)
                {
                    cellAnchor = new Xdr.AbsoluteAnchor(new Xdr.Position() { X = 0, Y = 0 });
                }
                else if (markerCount == 1)
                {
                    cellAnchor = new Xdr.OneCellAnchor(
                        XLMarkerConverter.Convert<Xdr.FromMarker>(
                            markers.First(),
                            (x) => CalcEmuScale(x, imageResX),
                            (y) => CalcEmuScale(y, imageResY)));
                }
                else if (markerCount == 2)
                {
                    var from = markers.First();
                    var to = markers.Last();
                    if (
                        from.RowIndex > to.RowIndex ||
                        from.ColumnIndex > to.ColumnIndex ||
                        (from.RowIndex == to.RowIndex && from.RowOffsetPx > to.RowOffsetPx) ||
                        (from.ColumnIndex == to.ColumnIndex && from.ColumnOffsetPx > to.ColumnOffsetPx)
                        )
                    {
                        throw new ArgumentException("positions of second marker must be larger than those of first marker");
                    }

                    cellAnchor = new Xdr.TwoCellAnchor(
                        XLMarkerConverter.Convert<Xdr.FromMarker>(
                            from,
                            (x) => CalcEmuScale(x, imageResX),
                            (y) => CalcEmuScale(y, imageResY)),
                        XLMarkerConverter.Convert<Xdr.ToMarker>(
                            to,
                            (x) => CalcEmuScale(x, imageResX),
                            (y) => CalcEmuScale(y, imageResY)));
                }
                else
                {
                    throw new ArgumentException("invalid markers count: " + markers.Count());
                }
            }

            var widthEmu = CalcEmuScale(picture.WidthPx, imageResX);
            var heightEmu = CalcEmuScale(picture.HeightPx, imageResY);

            cellAnchor.Append(
                new Xdr.Extent() { Cx = widthEmu, Cy = heightEmu, },

                new Xdr.Picture(
                    new Xdr.NonVisualPictureProperties(
                        new Xdr.NonVisualDrawingProperties()
                        {
                            Id = nvpId,
                            Name = (!string.IsNullOrEmpty(picture.Name)) ? picture.Name : nvpId.ToString() + "_" + Path.GetFileNameWithoutExtension(picture.FilePath),
                            Description = (!string.IsNullOrEmpty(picture.Description)) ? picture.Description : nvpId.ToString() + "_" + Path.GetFileNameWithoutExtension(picture.FilePath),
                        },
                        new Xdr.NonVisualPictureDrawingProperties(pictureLocks)
                    ),
                    new Xdr.BlipFill(
                        new A.Blip() { Embed = drawingsPart.GetIdOfPart(imagePart), CompressionState = A.BlipCompressionValues.Print },
                        new A.Stretch(new A.FillRectangle())
                    ),
                    new Xdr.ShapeProperties(
                        new A.Transform2D(
                            new A.Offset() { X = 0, Y = 0, },
                            new A.Extents() { Cx = widthEmu, Cy = heightEmu }
                        ),
                        new A.PresetGeometry() { Preset = A.ShapeTypeValues.Rectangle }
                    )
                ),
                new Xdr.ClientData()
            );

            sheetDrawing.Append(cellAnchor);

            #if false
            var errors = new DocumentFormat.OpenXml.Validation.OpenXmlValidator().Validate(worksheetPart);
            foreach (var error in errors)
            {
                Console.WriteLine(error.Description);
            }
            if (errors.Count() > 0) Console.Read();
            #endif
        }
예제 #6
0
        static void InsertImageTest(Sheet sheet, WorksheetPart sheetPart)
        {
            var filepath = System.IO.Path.GetFullPath(@"..\..\test.jpg");
            int widthPx = 100, heightPx = 100;
            int rowIndex = 2, colomnIndex = 3;
            int rowOffsetPx = 5, columnOffsetPx = 10;

            var imageType      = ImagePartType.Jpeg;
            var noChangeAspect = true;
            var noCrop         = false;
            var noMove         = false;
            var noResize       = false;
            var noRotation     = false;
            var noSelection    = false;

            float imageResX, imageResY;

            using (var bmp = Image.FromFile(filepath) as Bitmap)
            {
                imageResX = bmp.HorizontalResolution;
                imageResY = bmp.VerticalResolution;
            }
            var widthEmu        = CalcEmuScale(widthPx, imageResX);
            var heightEmu       = CalcEmuScale(heightPx, imageResY);
            var columnOffsetEmu = CalcEmuScale(columnOffsetPx, imageResY);
            var rowOffsetEmu    = CalcEmuScale(rowOffsetPx, imageResX);

            var drawingsPart = sheetPart.DrawingsPart ?? sheetPart.AddNewPart <DrawingsPart>();

            if (!sheetPart.Worksheet.ChildElements.OfType <Drawing>().Any())
            {
                sheetPart.Worksheet.Append(new Drawing()
                {
                    Id = sheetPart.GetIdOfPart(drawingsPart)
                });
            }

            if (drawingsPart.WorksheetDrawing == null)
            {
                drawingsPart.WorksheetDrawing = new Xdr.WorksheetDrawing();
            }
            var sheetDrawing = drawingsPart.WorksheetDrawing;

            var imagePart = drawingsPart.AddImagePart(imageType);

            using (var stream = new FileStream(filepath, FileMode.Open))
            {
                imagePart.FeedData(stream);
            }

            var nvps  = sheetDrawing.Descendants <Xdr.NonVisualDrawingProperties>();
            var nvpId = (nvps.Count() > 0) ? (UInt32Value)nvps.Max(prop => prop.Id.Value) + 1 : 1U;

            var pictureLocks = new A.PictureLocks()
            {
                NoChangeAspect = noChangeAspect,
                NoCrop         = noCrop,
                NoMove         = noMove,
                NoResize       = noResize,
                NoRotation     = noRotation,
                NoSelection    = noSelection,
            };

            var oneCellAnchor = new Xdr.OneCellAnchor(
                new Xdr.FromMarker()
            {
                ColumnId     = new Xdr.ColumnId((colomnIndex - 1).ToString()),
                RowId        = new Xdr.RowId((rowIndex - 1).ToString()),
                ColumnOffset = new Xdr.ColumnOffset(columnOffsetEmu.ToString()),
                RowOffset    = new Xdr.RowOffset(rowOffsetEmu.ToString()),
            },

                new Xdr.Extent()
            {
                Cx = widthEmu, Cy = heightEmu,
            },

                new Xdr.Picture(
                    new Xdr.NonVisualPictureProperties(
                        new Xdr.NonVisualDrawingProperties()
            {
                Id = nvpId, Name = Path.GetFileName(filepath), Description = filepath,
            },
                        new Xdr.NonVisualPictureDrawingProperties(pictureLocks)
                        ),
                    new Xdr.BlipFill(
                        new A.Blip()
            {
                Embed = drawingsPart.GetIdOfPart(imagePart), CompressionState = A.BlipCompressionValues.Print
            },
                        new A.Stretch(new A.FillRectangle())
                        ),
                    new Xdr.ShapeProperties(
                        new A.Transform2D(
                            new A.Offset()
            {
                X = 0, Y = 0,
            },
                            new A.Extents()
            {
                Cx = widthEmu, Cy = heightEmu
            }
                            ),
                        new A.PresetGeometry()
            {
                Preset = A.ShapeTypeValues.Rectangle
            }
                        )
                    ),
                new Xdr.ClientData());

            sheetDrawing.Append(oneCellAnchor);

            var errors = new DocumentFormat.OpenXml.Validation.OpenXmlValidator().Validate(sheetPart);

            foreach (var err in errors)
            {
                Console.WriteLine(err.Description);
            }
            if (errors.Count() > 0)
            {
                Console.Read();
            }
        }