public static void Run() { // ExStart:ExtractTextFromPageRegion // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); // Open document Document pdfDocument = new Document(dataDir + "ExtractTextAll.pdf"); // Create TextAbsorber object to extract text TextAbsorber absorber = new TextAbsorber(); absorber.TextSearchOptions.LimitToPageBounds = true; absorber.TextSearchOptions.Rectangle = new Aspose.Pdf.Rectangle(100, 200, 250, 350); // Accept the absorber for first page pdfDocument.Pages[1].Accept(absorber); // Get the extracted text string extractedText = absorber.Text; // Create a writer and open the file TextWriter tw = new StreamWriter(dataDir + "extracted-text.txt"); // Write a line of text to the file tw.WriteLine(extractedText); // Close the stream tw.Close(); // ExEnd:ExtractTextFromPageRegion }
/// <summary> /// Finds all the views in the active document. /// </summary> /// <param name="doc">the active document</param> public static ViewSet GetAllViews (Document doc) { ViewSet allViews = new ViewSet(); FilteredElementCollector fec = new FilteredElementCollector(doc); ElementClassFilter elementsAreWanted = new ElementClassFilter(typeof(FloorType)); fec.WherePasses(elementsAreWanted); List<Element> elements = fec.ToElements() as List<Element>; foreach (Element element in elements) { Autodesk.Revit.DB.View view = element as Autodesk.Revit.DB.View; if (null == view) { continue; } else { ElementType objType = doc.GetElement(view.GetTypeId()) as ElementType; if (null == objType || objType.Name.Equals("Drawing Sheet")) { continue; } else { allViews.Insert(view); } } } return allViews; }
private async Task<Document> FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // Create an editor to do all the transformations. This allows us to fix all // the diagnostics in a clean manner. If we used the normal batch fix provider // then it might fail to apply all the individual text changes as many of the // changes produced by the diff might end up overlapping others. var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); var options = document.Project.Solution.Workspace.Options; // Attempt to use an out-var declaration if that's the style the user prefers. // Note: if using 'var' would cause a problem, we will use the actual type // of hte local. This is necessary in some cases (for example, when the // type of the out-var-decl affects overload resolution or generic instantiation). var useVarWhenDeclaringLocals = options.GetOption(CSharpCodeStyleOptions.UseVarWhenDeclaringLocals); var useImplicitTypeForIntrinsicTypes = options.GetOption(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes).Value; foreach (var diagnostic in diagnostics) { cancellationToken.ThrowIfCancellationRequested(); await AddEditsAsync(document, editor, diagnostic, useVarWhenDeclaringLocals, useImplicitTypeForIntrinsicTypes, cancellationToken).ConfigureAwait(false); } var newRoot = editor.GetChangedRoot(); return document.WithSyntaxRoot(newRoot); }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); string input = dataDir+ @"input.pdf"; using (Document pdfDocument = new Document(input)) { foreach (Field field in pdfDocument.Form) { SignatureField sf = field as SignatureField; if (sf != null) { Stream cerStream = sf.ExtractCertificate(); if (cerStream != null) { using (cerStream) { byte[] bytes = new byte[cerStream.Length]; using (FileStream fs = new FileStream(dataDir+ @"input.cer", FileMode.CreateNew)) { cerStream.Read(bytes, 0, bytes.Length); fs.Write(bytes, 0, bytes.Length); } } } } } } }
public void SitemapGeneratedWithSitemapItem(string hostname, string formatterString, string expected) { // Given Engine engine = new Engine(); engine.Trace.AddListener(new TestTraceListener()); if (!string.IsNullOrWhiteSpace(hostname)) engine.Metadata[Keys.Hostname] = hostname; Pipeline contentPipeline = new Pipeline("Content", engine, null); var doc = new Document(engine, contentPipeline).Clone("Test", new[] { new KeyValuePair<string, object>(Keys.RelativeFilePath, "sub/testfile.html") }); IDocument[] inputs = { doc }; IExecutionContext context = new ExecutionContext(engine, contentPipeline); Core.Modules.Metadata.Meta m = new Core.Modules.Metadata.Meta(Keys.SitemapItem, (d, c) => new SitemapItem(d[Keys.RelativeFilePath].ToString())); var outputs = m.Execute(inputs, context); Func<string, string> formatter = null; if (!string.IsNullOrWhiteSpace(formatterString)) formatter = f => string.Format(formatterString, f); // When Sitemap sitemap = new Sitemap(formatter); List<IDocument> results = sitemap.Execute(outputs.ToList(), context).ToList(); foreach (IDocument document in inputs.Concat(outputs.ToList())) { ((IDisposable)document).Dispose(); } // Then Assert.AreEqual(1, results.Count); Assert.That(results[0].Content, Does.Contain($"<loc>{expected}</loc>")); }
public static void Run() { // ExStart:ConvertPageRegionToDOM // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Images(); // Open document Document document = new Document( dataDir + "AddImage.pdf"); // Get rectangle of particular page region Aspose.Pdf.Rectangle pageRect = new Aspose.Pdf.Rectangle(20, 671, 693, 1125); // Set CropBox value as per rectangle of desired page region document.Pages[1].CropBox = pageRect; // Save cropped document into stream MemoryStream ms = new MemoryStream(); document.Save(ms); // Open cropped PDF document and convert to image document = new Document(ms); // Create Resolution object Resolution resolution = new Resolution(300); // Create PNG device with specified attributes PngDevice pngDevice = new PngDevice(resolution); dataDir = dataDir + "ConvertPageRegionToDOM_out.png"; // Convert a particular page and save the image to stream pngDevice.Process(document.Pages[1], dataDir); ms.Close(); // ExEnd:ConvertPageRegionToDOM Console.WriteLine("\nPage region converted to DOM successfully.\nFile saved at " + dataDir); }
public async Task<QuickInfoItem> GetItemAsync( Document document, int position, CancellationToken cancellationToken) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var token = await tree.GetTouchingTokenAsync(position, cancellationToken, findInsideTrivia: true).ConfigureAwait(false); var state = await GetQuickInfoItemAsync(document, token, position, cancellationToken).ConfigureAwait(false); if (state != null) { return state; } if (ShouldCheckPreviousToken(token)) { var previousToken = token.GetPreviousToken(); if ((state = await GetQuickInfoItemAsync(document, previousToken, position, cancellationToken).ConfigureAwait(false)) != null) { return state; } } return null; }
void MakePage(Document doc, Range range) { var table = doc.Tables.Add(range, (int)m_numberOfRows, 2); table.Rows.SetHeight(136.1F, WdRowHeightRule.wdRowHeightExactly); table.Columns.SetWidth(295.65F, WdRulerStyle.wdAdjustNone); // 297.65F table.LeftPadding = 0.75F; table.RightPadding = 0.75F; table.TopPadding = 5F; for (int row = 1; row <= m_numberOfRows; ++row) for (int col = 1; col <= 2; ++col) { string code = m_tr.ReadLine(); if (code == null) return; Console.WriteLine("Row:{0}, Col:{1}", row, col); var cell = table.Cell(row, col); cell.Range.Delete(); cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; PopCell(cell.Range, "Horsell Jubilation Balloon Race", isBold:true, fontSize:12, first:true); PopCell(cell.Range, "", fontSize:12); PopCell(cell.Range, "Notice to the finder of this balloon:", isBold:true); PopCell(cell.Range, "Please go to the website www.diamondballoons.info to register your details and the location of the balloon. By doing so you will be entered into a draw for a £25 Amazon Gift Voucher. Good luck and thank you!"); PopCell(cell.Range, code, false, 12, centre: true); PopCell(cell.Range, "", fontSize: 12); ++m_count; } }
public DocumentEditState this[Document document] { get { return _dataObject[document.Id.ToString(CultureInfo.InvariantCulture)]; } }
virtual public void CreatePdfTest() { String fileName = "xmp_metadata.pdf"; // step 1 Document document = new Document(); // step 2 PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(OUT_FOLDER + fileName, FileMode.Create)); MemoryStream os = new MemoryStream(); XmpWriter xmp = new XmpWriter(os, XmpWriter.UTF16, 2000); DublinCoreProperties.AddSubject(xmp.XmpMeta, "Hello World"); DublinCoreProperties.AddSubject(xmp.XmpMeta, "XMP & Metadata"); DublinCoreProperties.AddSubject(xmp.XmpMeta, "Metadata"); PdfProperties.SetKeywords(xmp.XmpMeta, "Hello World, XMP & Metadata, Metadata"); PdfProperties.SetVersion(xmp.XmpMeta, "1.4"); xmp.Close(); writer.XmpMetadata = os.ToArray(); // step 3 document.Open(); // step 4 document.Add(new Paragraph("Hello World")); // step 5 document.Close(); CompareResults(fileName, fileName); }
private void CalculateStats(Document document) { var all = document.Map.WorldSpawn.FindAll(); var solids = all.OfType<Solid>().ToList(); var faces = solids.SelectMany(x => x.Faces).ToList(); var entities = all.OfType<Entity>().ToList(); var numSolids = solids.Count; var numFaces = faces.Count; var numPointEnts = entities.Count(x => !x.HasChildren); var numSolidEnts = entities.Count(x => x.HasChildren); var uniqueTextures = faces.Select(x => x.Texture.Name).Distinct().ToList(); var numUniqueTextures = uniqueTextures.Count; var textureMemory = faces.Select(x => x.Texture.Texture) .Where(x => x != null) .Distinct() .Sum(x => x.Width * x.Height * 3); // 3 bytes per pixel var textureMemoryMb = textureMemory / (1024m * 1024m); var items = document.TextureCollection.GetItems(uniqueTextures); var packages = items.Select(x => x.Package).Distinct(); // todo texture memory, texture packages NumSolids.Text = numSolids.ToString(CultureInfo.CurrentCulture); NumFaces.Text = numFaces.ToString(CultureInfo.CurrentCulture); NumPointEntities.Text = numPointEnts.ToString(CultureInfo.CurrentCulture); NumSolidEntities.Text = numSolidEnts.ToString(CultureInfo.CurrentCulture); NumUniqueTextures.Text = numUniqueTextures.ToString(CultureInfo.CurrentCulture); // TextureMemory.Text = textureMemory.ToString(CultureInfo.CurrentCulture); TextureMemory.Text = textureMemory.ToString("#,##0", CultureInfo.CurrentCulture) + " bytes (" + textureMemoryMb.ToString("0.00", CultureInfo.CurrentCulture) + " MB)"; foreach (var tp in packages) { TexturePackages.Items.Add(tp); } }
public async Task<ExtractInterfaceTypeAnalysisResult> AnalyzeTypeAtPositionAsync( Document document, int position, TypeDiscoveryRule typeDiscoveryRule, CancellationToken cancellationToken) { var typeNode = GetTypeDeclaration(document, position, typeDiscoveryRule, cancellationToken); if (typeNode == null) { var errorMessage = FeaturesResources.CouldNotExtractInterfaceSelection; return new ExtractInterfaceTypeAnalysisResult(errorMessage); } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var type = semanticModel.GetDeclaredSymbol(typeNode, cancellationToken); if (type == null || type.Kind != SymbolKind.NamedType) { var errorMessage = FeaturesResources.CouldNotExtractInterfaceSelection; return new ExtractInterfaceTypeAnalysisResult(errorMessage); } var typeToExtractFrom = type as INamedTypeSymbol; var extractableMembers = typeToExtractFrom.GetMembers().Where(IsExtractableMember); if (!extractableMembers.Any()) { var errorMessage = FeaturesResources.CouldNotExtractInterfaceTypeMember; return new ExtractInterfaceTypeAnalysisResult(errorMessage); } return new ExtractInterfaceTypeAnalysisResult(this, document, typeNode, typeToExtractFrom, extractableMembers); }
public override bool CanExecute(IDictionary<string, object> parameter) { _document = _dte.ActiveDocument; if (_document == null || _document.ProjectItem == null || _document.ProjectItem.FileCodeModel == null) { MessageBox(ErrMessage); return false; } _serviceClass = GetClass(_document.ProjectItem.FileCodeModel.CodeElements); if (_serviceClass == null) { MessageBox(ErrMessage); return false; } _serviceInterface = GetServiceInterface(_serviceClass as CodeElement); if (_serviceInterface == null) { MessageBox(ErrMessage); return false; } _serviceName = _serviceClass.Name.Replace("AppService", ""); return true; }
///<summary>Inserts one Document into the database. Returns the new priKey.</summary> internal static long Insert(Document document) { if(DataConnection.DBtype==DatabaseType.Oracle) { document.DocNum=DbHelper.GetNextOracleKey("document","DocNum"); int loopcount=0; while(loopcount<100){ try { return Insert(document,true); } catch(Oracle.DataAccess.Client.OracleException ex){ if(ex.Number==1 && ex.Message.ToLower().Contains("unique constraint") && ex.Message.ToLower().Contains("violated")){ document.DocNum++; loopcount++; } else{ throw ex; } } } throw new ApplicationException("Insert failed. Could not generate primary key."); } else { return Insert(document,false); } }
GetAllSheets (Document doc) { ElementSet allSheets = new ElementSet(); FilteredElementCollector fec = new FilteredElementCollector(doc); ElementClassFilter elementsAreWanted = new ElementClassFilter(typeof(ViewSheet)); fec.WherePasses(elementsAreWanted); List<Element> elements = fec.ToElements() as List<Element>; foreach (Element element in elements) { ViewSheet viewSheet = element as ViewSheet; if (null == viewSheet) { continue; } else { ElementId objId = viewSheet.GetTypeId(); if (ElementId.InvalidElementId == objId) { continue; } else { allSheets.Insert(viewSheet); } } } return allSheets; }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_WorkingWithBookmarks(); // Load the source document. Document srcDoc = new Document(dataDir + "Template.doc"); // This is the bookmark whose content we want to copy. Bookmark srcBookmark = srcDoc.Range.Bookmarks["ntf010145060"]; // We will be adding to this document. Document dstDoc = new Document(); // Let's say we will be appending to the end of the body of the last section. CompositeNode dstNode = dstDoc.LastSection.Body; // It is a good idea to use this import context object because multiple nodes are being imported. // If you import multiple times without a single context, it will result in many styles created. NodeImporter importer = new NodeImporter(srcDoc, dstDoc, ImportFormatMode.KeepSourceFormatting); // Do it once. AppendBookmarkedText(importer, srcBookmark, dstNode); // Do it one more time for fun. AppendBookmarkedText(importer, srcBookmark, dstNode); // Save the finished document. dstDoc.Save(dataDir + "Template Out.doc"); Console.WriteLine("\nBookmark copied successfully.\nFile saved at " + dataDir + "Template Out.doc"); }
public static void Run() { // ExStart:GetXFAProperties // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Forms(); // Load XFA form Document doc = new Document(dataDir + "GetXFAProperties.pdf"); string[] names = doc.Form.XFA.FieldNames; // Set field values doc.Form.XFA[names[0]] = "Field 0"; doc.Form.XFA[names[1]] = "Field 1"; // Get field position Console.WriteLine(doc.Form.XFA.GetFieldTemplate(names[0]).Attributes["x"].Value); // Get field position Console.WriteLine(doc.Form.XFA.GetFieldTemplate(names[0]).Attributes["y"].Value); dataDir = dataDir + "Filled_XFA_out.pdf"; // Save the updated document doc.Save(dataDir); // ExEnd:GetXFAProperties Console.WriteLine("\nXFA fields properties retrieved successfully.\nFile saved at " + dataDir); }
protected void submitButton_Click(object sender, EventArgs e) { if (description.Text != "" && end.Text != "" && inId.Value != "" && Name.Text != "" && oName.Text != "" && start.Text != "" && venue.Text != "") { AmazonDynamoDBClient client = new AmazonDynamoDBClient(); Amazon.DynamoDBv2.DocumentModel.Table table = Amazon.DynamoDBv2.DocumentModel.Table.LoadTable(client, "Event"); var book = new Document(); book["description1"] = description.Text; //DateTime date2 = Convert.ToDateTime(end.Text); //string endDate = date2.ToString("dd/MM/yyyy"); book["endDate"] = end.Text; book["eventId"] = inId.Value; book["eventName"] = Name.Text; book["organiserName"] = oName.Text; //DateTime date1 = Convert.ToDateTime(start.Text); //string startDate = date1.ToString("dd/MM/yyyy"); book["startDate"] = start.Text; book["venue"] = venue.Text; table.PutItem(book); Response.Redirect("Events.aspx"); string script = "alert(\"Successfully created the Event.\");"; ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true); } else { string script = "alert(\"Please fill all the data correctly.\");"; ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true); } }
public static void Run() { // ExStart:ExtractContentBetweenBlockLevelNodes // The path to the documents directory. string dataDir = RunExamples.GetDataDir_WorkingWithDocument(); string fileName = "TestFile.doc"; Document doc = new Document(dataDir + fileName); Paragraph startPara = (Paragraph)doc.LastSection.GetChild(NodeType.Paragraph, 2, true); Table endTable = (Table)doc.LastSection.GetChild(NodeType.Table, 0, true); // Extract the content between these nodes in the document. Include these markers in the extraction. ArrayList extractedNodes = Common.ExtractContent(startPara, endTable, true); // Lets reverse the array to make inserting the content back into the document easier. extractedNodes.Reverse(); while (extractedNodes.Count > 0) { // Insert the last node from the reversed list endTable.ParentNode.InsertAfter((Node)extractedNodes[0], endTable); // Remove this node from the list after insertion. extractedNodes.RemoveAt(0); } dataDir = dataDir + RunExamples.GetOutputFilePath(fileName); // Save the generated document to disk. doc.Save(dataDir); // ExEnd:ExtractContentBetweenBlockLevelNodes Console.WriteLine("\nExtracted content betweenn the block level nodes successfully.\nFile saved at " + dataDir); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { // Get the access to the top most objects. UIApplication uiApp = commandData.Application; UIDocument uiDoc = uiApp.ActiveUIDocument; _app = uiApp.Application; _doc = uiDoc.Document; // (1) In eailer lab, CommandData command, we // learned how to access to the wallType. i.e., // here we'll take a look at more on the topic // of accessing to elements in the interal rvt // project database. ListFamilyTypes(); // (2) List instances of specific object class. ListInstances(); // (3) Find a specific family type. FindFamilyType(); // (4) Find specific instances, including filtering by parameters. FindInstance(); // (5) List all elements. ListAllElements(); // We are done. return Result.Succeeded; }
private void button2_Click(object sender, EventArgs e) { BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false); iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 12, iTextSharp.text.Font.ITALIC, BaseColor.DARK_GRAY); Document doc = new Document(iTextSharp.text.PageSize.LETTER,10,10,42,42); PdfWriter pdw = PdfWriter.GetInstance(doc, new FileStream(naziv + ".pdf", FileMode.Create)); doc.Open(); Paragraph p = new Paragraph("Word Count for : "+naziv,times); doc.Add(p); p.Alignment = 1; PdfPTable pdt = new PdfPTable(2); pdt.HorizontalAlignment = 1; pdt.SpacingBefore = 20f; pdt.SpacingAfter = 20f; pdt.AddCell("Word"); pdt.AddCell("No of repetitions"); foreach (Rijec r in lista_rijeci) { pdt.AddCell(r.Tekst); pdt.AddCell(Convert.ToString(r.Ponavljanje)); } using (MemoryStream stream = new MemoryStream()) { chart1.SaveImage(stream, ChartImageFormat.Png); iTextSharp.text.Image chartImage = iTextSharp.text.Image.GetInstance(stream.GetBuffer()); chartImage.ScalePercent(75f); chartImage.Alignment = 1; doc.Add(chartImage); } doc.Add(pdt); doc.Close(); MessageBox.Show("PDF created!"); }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Note.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); Dictionary<string, string> replacements = new Dictionary<string, string>(); replacements.Add("Some task here", "New Text Here"); // Load the document into Aspose.Note. Document oneFile = new Document(dataDir + "Aspose.one"); IList<Node> pageNodes = oneFile.GetChildNodes(NodeType.Page); CompositeNode<Page> compositeNode = (CompositeNode<Page>)pageNodes[0]; // Get all RichText nodes IList<Node> textNodes = compositeNode.GetChildNodes(NodeType.RichText); foreach (Node node in textNodes) { foreach (KeyValuePair<string, string> kvp in replacements) { RichText richText = (RichText)node; if (richText != null && richText.Text.Contains(kvp.Key)) { // Replace text of a shape richText.Text = richText.Text.Replace(kvp.Key, kvp.Value); } } } // Save to any supported file format oneFile.Save(dataDir + "Output.pdf", SaveFormat.Pdf); }
public async Task<BraceMatchingResult?> FindBracesAsync( Document document, int position, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(position); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (position < text.Length && this.IsBrace(text[position])) { if (token.RawKind == _openBrace.Kind && AllowedForToken(token)) { var leftToken = token; if (TryFindMatchingToken(leftToken, out var rightToken)) { return new BraceMatchingResult(leftToken.Span, rightToken.Span); } } else if (token.RawKind == _closeBrace.Kind && AllowedForToken(token)) { var rightToken = token; if (TryFindMatchingToken(rightToken, out var leftToken)) { return new BraceMatchingResult(leftToken.Span, rightToken.Span); } } } return null; }
/// <summary> /// Fill the target document with random content /// </summary> /// <param Name="doc"></param> public void GenerateContent(Document doc) { //Starting with the start symbol, randomly navigate the Finite State Machine //Filling the target document with content until it hits the terminate symbol Section next = StartSymbol; while ((next = next.generate(doc)) != null) { } }
public DocEdit(Form parent, Document doc) { MdiParent = parent; InitializeComponent(); m_doc = doc; doc.AddView(this); }
public void SetGenerateTypeOptions( Accessibility accessibility = Accessibility.NotApplicable, TypeKind typeKind = TypeKind.Class, string typeName = null, Project project = null, bool isNewFile = false, string newFileName = null, IList<string> folders = null, string fullFilePath = null, Document existingDocument = null, bool areFoldersValidIdentifiers = true, string defaultNamespace = null, bool isCancelled = false) { Accessibility = accessibility; TypeKind = typeKind; TypeName = typeName; Project = project; IsNewFile = isNewFile; NewFileName = newFileName; Folders = folders; FullFilePath = fullFilePath; ExistingDocument = existingDocument; AreFoldersValidIdentifiers = areFoldersValidIdentifiers; DefaultNamespace = defaultNamespace; IsCancelled = isCancelled; }
/// <summary> /// Creates a new HTML link element. /// </summary> public HtmlLinkElement(Document owner, String prefix = null) : base(owner, Tags.Link, prefix, NodeFlags.Special | NodeFlags.SelfClosing) { RegisterAttributeObserver(AttributeNames.Media, UpdateMedia); RegisterAttributeObserver(AttributeNames.Disabled, UpdateDisabled); RegisterAttributeObserver(AttributeNames.Href, value => UpdateSource(value)); }
public GenerateTypeOptionsResult GetGenerateTypeOptions( string className, GenerateTypeDialogOptions generateTypeDialogOptions, Document document, INotificationService notificationService, IProjectManagementService projectManagementService, ISyntaxFactsService syntaxFactsService) { // Storing the actual values ClassName = className; GenerateTypeDialogOptions = generateTypeDialogOptions; if (DefaultNamespace == null) { DefaultNamespace = projectManagementService.GetDefaultNamespace(Project, Project?.Solution.Workspace); } return new GenerateTypeOptionsResult( accessibility: Accessibility, typeKind: TypeKind, typeName: TypeName, project: Project, isNewFile: IsNewFile, newFileName: NewFileName, folders: Folders, fullFilePath: FullFilePath, existingDocument: ExistingDocument, areFoldersValidIdentifiers: AreFoldersValidIdentifiers, defaultNamespace: DefaultNamespace, isCancelled: IsCancelled); }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Bookmarks(); //open document Document pdfDocument = new Document(dataDir + "AddChildBookmark.pdf"); //create a parent bookmark object OutlineItemCollection pdfOutline = new OutlineItemCollection(pdfDocument.Outlines); pdfOutline.Title = "Parent Outline"; pdfOutline.Italic = true; pdfOutline.Bold = true; //set the destination page number pdfOutline.Destination = new GoToAction(2); //create a child bookmark object OutlineItemCollection pdfChildOutline = new OutlineItemCollection(pdfDocument.Outlines); pdfChildOutline.Title = "Child Outline"; pdfChildOutline.Italic = true; pdfChildOutline.Bold = true; //set the destination page number for child outline pdfChildOutline.Destination = new GoToAction(1); //add child bookmark in parent bookmark's collection pdfOutline.Add(pdfChildOutline); //add parent bookmark in the document's outline collection. pdfDocument.Outlines.Add(pdfOutline); //save output pdfDocument.Save(dataDir + "AddChildBookmark_out.pdf"); }
private DParameterDataProvider(Document doc, ArgumentsResolutionResult argsResult, int startOffset) : base(startOffset) { this.doc = doc; args = argsResult; selIndex = args.CurrentlyCalledMethod; }
/// <summary> /// Retrieve all wall openings, /// including at start and end of wall. /// </summary> List<WallOpening2d> GetWallOpenings( Wall wall, View3D view ) { Document doc = wall.Document; Level level = doc.GetElement( wall.LevelId ) as Level; double elevation = level.Elevation; Curve c = ( wall.Location as LocationCurve ).Curve; XYZ wallOrigin = c.GetEndPoint( 0 ); XYZ wallEndPoint = c.GetEndPoint( 1 ); XYZ wallDirection = wallEndPoint - wallOrigin; double wallLength = wallDirection.GetLength(); wallDirection = wallDirection.Normalize(); UV offsetOut = _offset * new UV( wallDirection.X, wallDirection.Y ); XYZ rayStart = new XYZ( wallOrigin.X - offsetOut.U, wallOrigin.Y - offsetOut.V, elevation + _offset ); ReferenceIntersector intersector = new ReferenceIntersector( wall.Id, FindReferenceTarget.Face, view ); IList<ReferenceWithContext> refs = intersector.Find( rayStart, wallDirection ); // Extract the intersection points: // - only surfaces // - within wall length plus offset at each end // - sorted by proximity // - eliminating duplicates List<XYZ> pointList = new List<XYZ>( refs .Where<ReferenceWithContext>( r => IsSurface( r.GetReference() ) ) .Where<ReferenceWithContext>( r => r.Proximity < wallLength + _offset + _offset ) .OrderBy<ReferenceWithContext, double>( r => r.Proximity ) .Select<ReferenceWithContext, XYZ>( r => r.GetReference().GlobalPoint ) .Distinct<XYZ>( new XyzEqualityComparer() ) ); // Check if first point is at the wall start. // If so, the wall does not begin with an opening, // so that point can be removed. Else, add it. XYZ q = wallOrigin + _offset * XYZ.BasisZ; bool wallHasFaceAtStart = Util.IsEqual( pointList[0], q ); if( wallHasFaceAtStart ) { pointList.RemoveAll( p //=> _eps > p.DistanceTo( q ) ); => Util.IsEqual( p, q ) ); } else { pointList.Insert( 0, wallOrigin ); } // Check if last point is at the wall end. // If so, the wall does not end with an opening, // so that point can be removed. Else, add it. q = wallEndPoint + _offset * XYZ.BasisZ; bool wallHasFaceAtEnd = Util.IsEqual( pointList.Last(), q ); if( wallHasFaceAtEnd ) { pointList.RemoveAll( p //=> _eps > p.DistanceTo( q ) ); => Util.IsEqual( p, q ) ); } else { pointList.Add( wallEndPoint ); } int n = pointList.Count; Debug.Assert( IsEven( n ), "expected an even number of opening sides" ); var wallOpenings = new List<WallOpening2d>( n / 2 ); for( int i = 0; i < n; i += 2 ) { wallOpenings.Add( new WallOpening2d { Start = pointList[i], End = pointList[i + 1] } ); } return wallOpenings; }
/// <summary> /// 正则表达式替换文字加高亮和批注 /// </summary> /// <param name="doc">Aspose文档</param> /// <param name="initialText"></param> /// <param name="commentText">批注文档</param> public ReplaceEvaluatorFindAndHighlightWithComment(Document doc, string initialText, string commentText) { _doc = doc; _initialText = initialText; _commentText = commentText; }
public ReplaceEvaluatorFindAndHighlight(Document doc) { _doc = doc; }
protected void ImageButton3_Click(object sender, ImageClickEventArgs e) { try { //souce for reference INSE 6260 /////http://csharp-video-tutorials.blogspot.ca/2013/04/export-gridview-to-pdf-in-aspnet-part-58.html int columnsCount = GVClientBillList.HeaderRow.Cells.Count; PdfPTable pdfTable = new PdfPTable(columnsCount); foreach (TableCell gridViewHeaderCell in GVClientBillList.HeaderRow.Cells) { Font font = new Font(); font.Color = new BaseColor(GVClientBillList.HeaderStyle.ForeColor); PdfPCell pdfCell = new PdfPCell(new Phrase(gridViewHeaderCell.Text, font)); pdfCell.BackgroundColor = new BaseColor(GVClientBillList.HeaderStyle.BackColor); pdfTable.AddCell(pdfCell); } foreach (GridViewRow gridViewRow in GVClientBillList.Rows) { if (gridViewRow.RowType == DataControlRowType.DataRow) { foreach (TableCell gridViewCell in gridViewRow.Cells) { Font font = new Font(); font.Color = new BaseColor(GVClientBillList.RowStyle.ForeColor); PdfPCell pdfCell = new PdfPCell(new Phrase(gridViewCell.Text, font)); pdfCell.BackgroundColor = new BaseColor(GVClientBillList.RowStyle.BackColor); pdfTable.AddCell(pdfCell); } } } Document pdfDocument = new Document(PageSize.A4, 10f, 10f, 10f, 10f); PdfWriter.GetInstance(pdfDocument, Response.OutputStream); pdfDocument.Open(); pdfDocument.Add(pdfTable); pdfDocument.Close(); DateTime dt1 = DateTime.Now; string dt = dt1.ToShortDateString(); Response.ContentType = "application/pdf"; Response.AppendHeader("content-disposition", "attachment;filename=" + dt + "Statement.pdf"); Response.Write(pdfDocument); Response.Flush(); Response.End(); } catch (Exception ex) { LblError.Visible = true; LblError.Text = ex.ToString(); } }
public virtual void SearchIndex(Directory dir, string oldName) { //QueryParser parser = new QueryParser("contents", new MockAnalyzer(random)); //Query query = parser.parse("handle:1"); IndexReader reader = DirectoryReader.Open(dir); IndexSearcher searcher = new IndexSearcher(reader); TestUtil.CheckIndex(dir); // true if this is a 4.0+ index bool is40Index = MultiFields.GetMergedFieldInfos(reader).FieldInfo("content5") != null; IBits liveDocs = MultiFields.GetLiveDocs(reader); for (int i = 0; i < 35; i++) { if (liveDocs.Get(i)) { Document d = reader.Document(i); IList <IIndexableField> fields = d.Fields; bool isProxDoc = d.GetField("content3") == null; if (isProxDoc) { int numFields = is40Index ? 7 : 5; Assert.AreEqual(numFields, fields.Count); IIndexableField f = d.GetField("id"); Assert.AreEqual("" + i, f.GetStringValue()); f = d.GetField("utf8"); Assert.AreEqual("Lu\uD834\uDD1Ece\uD834\uDD60ne \u0000 \u2620 ab\ud917\udc17cd", f.GetStringValue()); f = d.GetField("autf8"); Assert.AreEqual("Lu\uD834\uDD1Ece\uD834\uDD60ne \u0000 \u2620 ab\ud917\udc17cd", f.GetStringValue()); f = d.GetField("content2"); Assert.AreEqual("here is more content with aaa aaa aaa", f.GetStringValue()); f = d.GetField("fie\u2C77ld"); Assert.AreEqual("field with non-ascii name", f.GetStringValue()); } Fields tfvFields = reader.GetTermVectors(i); Assert.IsNotNull(tfvFields, "i=" + i); Terms tfv = tfvFields.GetTerms("utf8"); Assert.IsNotNull(tfv, "docID=" + i + " index=" + oldName); } else { // Only ID 7 is deleted Assert.AreEqual(7, i); } } if (is40Index) { // check docvalues fields NumericDocValues dvByte = MultiDocValues.GetNumericValues(reader, "dvByte"); BinaryDocValues dvBytesDerefFixed = MultiDocValues.GetBinaryValues(reader, "dvBytesDerefFixed"); BinaryDocValues dvBytesDerefVar = MultiDocValues.GetBinaryValues(reader, "dvBytesDerefVar"); SortedDocValues dvBytesSortedFixed = MultiDocValues.GetSortedValues(reader, "dvBytesSortedFixed"); SortedDocValues dvBytesSortedVar = MultiDocValues.GetSortedValues(reader, "dvBytesSortedVar"); BinaryDocValues dvBytesStraightFixed = MultiDocValues.GetBinaryValues(reader, "dvBytesStraightFixed"); BinaryDocValues dvBytesStraightVar = MultiDocValues.GetBinaryValues(reader, "dvBytesStraightVar"); NumericDocValues dvDouble = MultiDocValues.GetNumericValues(reader, "dvDouble"); NumericDocValues dvFloat = MultiDocValues.GetNumericValues(reader, "dvFloat"); NumericDocValues dvInt = MultiDocValues.GetNumericValues(reader, "dvInt"); NumericDocValues dvLong = MultiDocValues.GetNumericValues(reader, "dvLong"); NumericDocValues dvPacked = MultiDocValues.GetNumericValues(reader, "dvPacked"); NumericDocValues dvShort = MultiDocValues.GetNumericValues(reader, "dvShort"); for (int i = 0; i < 35; i++) { int id = Convert.ToInt32(reader.Document(i).Get("id")); Assert.AreEqual(id, dvByte.Get(i)); sbyte[] bytes = new sbyte[] { (sbyte)((int)((uint)id >> 24)), (sbyte)((int)((uint)id >> 16)), (sbyte)((int)((uint)id >> 8)), (sbyte)id }; BytesRef expectedRef = new BytesRef((byte[])(Array)bytes); BytesRef scratch = new BytesRef(); dvBytesDerefFixed.Get(i, scratch); Assert.AreEqual(expectedRef, scratch); dvBytesDerefVar.Get(i, scratch); Assert.AreEqual(expectedRef, scratch); dvBytesSortedFixed.Get(i, scratch); Assert.AreEqual(expectedRef, scratch); dvBytesSortedVar.Get(i, scratch); Assert.AreEqual(expectedRef, scratch); dvBytesStraightFixed.Get(i, scratch); Assert.AreEqual(expectedRef, scratch); dvBytesStraightVar.Get(i, scratch); Assert.AreEqual(expectedRef, scratch); Assert.AreEqual((double)id, BitConverter.Int64BitsToDouble(dvDouble.Get(i)), 0D); Assert.AreEqual((float)id, Number.Int32BitsToSingle((int)dvFloat.Get(i)), 0F); Assert.AreEqual(id, dvInt.Get(i)); Assert.AreEqual(id, dvLong.Get(i)); Assert.AreEqual(id, dvPacked.Get(i)); Assert.AreEqual(id, dvShort.Get(i)); } } ScoreDoc[] hits = searcher.Search(new TermQuery(new Term("content", "aaa")), null, 1000).ScoreDocs; // First document should be #21 since it's norm was // increased: Document d_ = searcher.IndexReader.Document(hits[0].Doc); assertEquals("didn't get the right document first", "21", d_.Get("id")); DoTestHits(hits, 34, searcher.IndexReader); if (is40Index) { hits = searcher.Search(new TermQuery(new Term("content5", "aaa")), null, 1000).ScoreDocs; DoTestHits(hits, 34, searcher.IndexReader); hits = searcher.Search(new TermQuery(new Term("content6", "aaa")), null, 1000).ScoreDocs; DoTestHits(hits, 34, searcher.IndexReader); } hits = searcher.Search(new TermQuery(new Term("utf8", "\u0000")), null, 1000).ScoreDocs; Assert.AreEqual(34, hits.Length); hits = searcher.Search(new TermQuery(new Term("utf8", "Lu\uD834\uDD1Ece\uD834\uDD60ne")), null, 1000).ScoreDocs; Assert.AreEqual(34, hits.Length); hits = searcher.Search(new TermQuery(new Term("utf8", "ab\ud917\udc17cd")), null, 1000).ScoreDocs; Assert.AreEqual(34, hits.Length); reader.Dispose(); }
public void GenerateResultReport() { var doc = new Document(); // DocumentBuilder provides members to easily add content to a document. DocumentBuilder builder = new DocumentBuilder(doc); if (reportError.Count != 0) { builder.Writeln("错误列表"); int i = 1; //计数 builder.StartTable(); builder.InsertCell(); builder.Write("序号"); builder.InsertCell(); builder.Write("编号"); builder.InsertCell(); builder.Write("名称"); builder.InsertCell(); builder.Write("位置"); builder.InsertCell(); builder.Write("说明"); builder.InsertCell(); builder.Write("批注"); builder.EndRow(); foreach (var e in reportError) { builder.InsertCell(); builder.Write(i.ToString()); builder.InsertCell(); builder.Write(((int)e.No).ToString()); builder.InsertCell(); builder.Write(e.Name); builder.InsertCell(); builder.Write(e.Position); builder.InsertCell(); builder.Write(e.Description); builder.InsertCell(); builder.Write(e.HasComment.ToString()); builder.EndRow(); i += 1; } builder.EndTable(); } if (reportWarnning.Count != 0) { builder.Writeln("警告列表"); int i = 1; //计数 builder.StartTable(); builder.InsertCell(); builder.Write("序号"); builder.InsertCell(); builder.Write("编号"); builder.InsertCell(); builder.Write("名称"); builder.InsertCell(); builder.Write("位置"); builder.InsertCell(); builder.Write("说明"); builder.InsertCell(); builder.Write("批注"); builder.EndRow(); foreach (var w in reportWarnning) { builder.InsertCell(); builder.Write(i.ToString()); builder.InsertCell(); builder.Write(((int)w.No).ToString()); builder.InsertCell(); builder.Write(w.Name); builder.InsertCell(); builder.Write(w.Position); builder.InsertCell(); builder.Write(w.Description); builder.InsertCell(); builder.Write(w.HasComment.ToString()); builder.EndRow(); i += 1; } builder.EndTable(); } // Save the document in DOCX format. The format to save as is inferred from the extension of the file name. // Aspose.Words supports saving any document in many more formats. doc.Save("校核结果.docx"); }